我使用subprocess
在两个进程之间交换数据
我使用以下内容编辑 repeat.py
文件:
此文件是 http://www.doughellmann.com/PyMOTW/subprocess/ 中的示例
import sys
sys.stderr.write('repeater.py: starting\n')
sys.stderr.flush()
while True:
next_line = sys.stdin.readline()
if not next_line:
break
sys.stdout.write(next_line)
sys.stdout.flush()
sys.stderr.write('repeater.py: exiting\n')
sys.stderr.flush()
并在ipython
中运行此文件
In [1]: import subprocess
In [2]: f=subprocess.Popen(['python','~/repeat.py'],shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE)
In [3]: f.stdin.write('teststs\n')
In [4]: f.communicate()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'teststs' is not defined
Out[4]: ('', None)
为什么没有定义teststs
?
最佳答案
您似乎正在启动交互式 Python session ,而不是运行 repeat.py
。尝试删除 shell=True
,它与参数列表一起没有意义。 (顺便说一句,使用 shell=True
几乎总是一个坏主意。)
关于python - 子进程无法从其他进程获取标准输入输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11563303/