gpt4 book ai didi

python - subprocess.Popen() IO 重定向

转载 作者:太空狗 更新时间:2023-10-29 18:24:39 31 4
gpt4 key购买 nike

尝试将子进程的输出重定向到文件。

服务器.py:

while 1:
print "Count " + str(count)
sys.stdout.flush()
count = count + 1
time.sleep(1)

劳彻:

cmd = './server.py >temp.txt'
args = shlex.split(cmd)
server = subprocess.Popen( args )

输出出现在屏幕上,temp.txt 保持为空。我做错了什么?

作为背景,我正在 try catch 已编写程序的输出。

我不能使用:

server = subprocess.Popen(
[exe_name],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)

因为程序可能不会刷新。相反,我打算通过 fifo 重定向输出。如果我手动启动 server.py 这很好用,但如果我 Popen() 显然不行,因为重定向不起作用。ps -aux 显示 server.py 已正确启动。

最佳答案

或者,您可以将 stdout 参数与文件对象一起使用:

with open('temp.txt', 'w') as output:
server = subprocess.Popen('./server.py', stdout=output)
server.communicate()

documentation 中所述:

stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None.

关于python - subprocess.Popen() IO 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8902206/

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