如何在 Popen 中使用 fifo 命名管道作为标准输入 python

How to use fifo named pipe as stdin in Popen python

如何让 Popen 使用 fifo 命名管道作为标准输入?

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)

如果我 运行 这个脚本和终端 window

echo "Something" > myfifo

进程退出 process.stdin None。它似乎没有从 fifo 获取标准输入。

根据 documentation,只有当该字段的参数是 PIPE 时,Popen.stdin 才不是 None,而在您的代码中并非如此。

这段代码对我来说工作正常,它按预期打印“第 1 行”和“第 2 行”(来自子进程)

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)