gpt4 book ai didi

python ,子进程: reading output from subprocess

转载 作者:太空狗 更新时间:2023-10-29 17:27:58 25 4
gpt4 key购买 nike

我有以下脚本:

#!/usr/bin/python

while True:
x = raw_input()
print x[::-1]

我从 ipython 调用它:

In [5]: p = Popen('./script.py', stdin=PIPE)

In [6]: p.stdin.write('abc\n')
cba

而且效果很好。

但是,当我这样做时:

In [7]: p = Popen('./script.py', stdin=PIPE, stdout=PIPE)

In [8]: p.stdin.write('abc\n')

In [9]: p.stdout.read()

解释器挂起。我究竟做错了什么?我希望能够多次从另一个进程写入和读取,以将一些任务传递给这个进程。我需要做哪些不同的事情?

编辑 1

如果我使用communicate,我会得到这个:

In [7]: p = Popen('./script.py', stdin=PIPE, stdout=PIPE)

In [8]: p.communicate('abc\n')
Traceback (most recent call last):
File "./script.py", line 4, in <module>
x = raw_input()
EOFError: EOF when reading a line
Out[8]: ('cba\n', None)

编辑 2

我试过冲洗:

#!/usr/bin/python

import sys

while True:
x = raw_input()
print x[::-1]
sys.stdout.flush()

这里:

In [5]: from subprocess import PIPE, Popen

In [6]: p = Popen('./script.py', stdin=PIPE, stdout=PIPE)

In [7]: p.stdin.write('abc')

In [8]: p.stdin.flush()

In [9]: p.stdout.read()

但它再次挂起。

最佳答案

我认为这里有两个问题:

1) 您的父脚本调用 p.stdout.read(),它将读取所有数据直到文件结束。但是,您的子脚本在无限循环中运行,因此永远不会发生文件结束。可能你想要 p.stdout.readline()

2) 在交互模式下,大多数程序一次只缓冲一行。当从另一个程序运行时,它们会缓冲更多。缓冲在许多情况下提高了效率,但在两个程序需要交互通信时会导致问题。

p.stdin.write('abc\n')之后添加:

p.stdin.flush()

在您的子进程脚本中,在 print x[::-1] 之后在循环中添加以下内容:

sys.stdout.flush()

(和顶部的 import sys)

关于 python ,子进程: reading output from subprocess,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3804727/

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