python - 子进程无法从其他进程获取标准输入输入

标签 python multiprocessing subprocess

我使用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/

相关文章:

python - python 中的一行 if else 条件

python - 遍历条件字典时出现逻辑评估错误

python 结构。错误: 'i' format requires -2147483648 <= number <= 2147483647

python - 多处理模块中的 ThreadPool 与 Pool 有什么区别?

python - 为什么这个 subprocess.check_call() 不起作用?

python - 在Python中导入创建环境变量?

python - pandas 读取 excel 结果为 "not a zip file"

python - 从 Applescript 调用 Python 脚本

c - 系统如何知道没有更多未等待的 child

python - 文件相关操作 python 子进程 vs 原生 python