gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:51:28 24 4
gpt4 key购买 nike

如何让 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)

如果我在终端窗口中运行这个脚本

echo "Something" > myfifo

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

最佳答案

根据documentation , Popen.stdin只是不是 None如果该字段的参数是 PIPE ,这在您的代码中不是这种情况。

这段代码对我来说工作正常,它按预期打印“第 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)

关于python - 如何在 Popen python 中使用 fifo 命名管道作为标准输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63132778/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com