如何在Popen python中使用fifo命名管道作为stdin [英] How to use fifo named pipe as stdin in Popen python
本文介绍了如何在Popen python中使用fifo命名管道作为stdin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何让 Popen 使用一个名为管道的 fifo 作为标准输入?
How do I make Popen use a fifo named pipe as stdin?
import subprocess
import os
import time
FNAME = 'myfifo'
os.mkfifo(FNAME, mode=0o777)
f = os.open(FNAME, os.O_RDONLY)
process = subprocess.Popen(
'wait2.sh',
shell=True,
stdout=subprocess.PIPE,
stdin=f,
stderr=subprocess.PIPE,
universal_newlines=True,
)
while process.poll() is None:
time.sleep(1)
print("process.stdin", process.stdin)
如果我在终端窗口中运行此脚本
If I run this script and in a terminal window
echo "Something" > myfifo
进程以 process.stdin None
退出.似乎它没有从 fifo 中获取标准输入.
The process exits with process.stdin None
. It seems its not getting the stdin from the fifo.
推荐答案
根据 文档,如果该字段的参数是 PIPE
,则 Popen.stdin
不是 None
,即在您的代码中并非如此.
According to the documentation, the Popen.stdin
is only not None
if the argument for that field was PIPE
, which is not the case in your code.
这段代码对我来说很好用,它打印第 1 行";和第2行"(来自子进程)如预期
This code works fine for me, it prints "Line 1" and "Line 2" (from the child process) as expected
import subprocess
import os
import time
FNAME = 'myfifo'
os.mkfifo(FNAME, mode=0o777)
# Open read end of pipe. Open this in non-blocking mode since otherwise it
# may block until another process/threads opens the pipe for writing.
stdin = os.open(FNAME, os.O_RDONLY | os.O_NONBLOCK)
# Open the write end of pipe.
tochild = os.open(FNAME, os.O_WRONLY)
print('Pipe open (%d, %d)' % (stdin, tochild))
process = subprocess.Popen(
['/usr/bin/cat'],
shell=True,
stdout=None,
stdin=stdin,
stderr=None,
universal_newlines=True,
)
print('child started: %s (%s)' % (str(process), str(process.stdin)))
# Close read end of pipe since it is not used in the parent process.
os.close(stdin)
# Write to child then close the write end to indicate to the child that
# the input is complete.
print('writing to child ...')
os.write(tochild, bytes('Line 1\n', 'utf-8'))
os.write(tochild, bytes('Line 2\n', 'utf-8'))
print('data written')
os.close(tochild)
# Wait for child to complete.
process.wait()
os.unlink(FNAME)
这篇关于如何在Popen python中使用fifo命名管道作为stdin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文