【问题标题】:subprocess can't get the stdin input from other process子进程无法从其他进程获取标准输入
【发布时间】:2012-07-18 18:47:33
【问题描述】:

我使用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 multiprocessing subprocess


【解决方案1】:

您似乎正在启动交互式 Python 会话,而不是运行 repeat.py。尝试删除shell=True,与参数列表一起使用没有意义。 (顺便说一句,使用shell=True 几乎总是一个坏主意。)

【讨论】:

    【解决方案2】:

    这适用于前 5 次按键的一些奇怪行为。我不知道为什么。之后如果工作正常,我们可以访问ls -lcd,当按下 UP 时之前的命令,似乎命令行具有完整的功能。

    #!/bin/python3
    
    import subprocess
    import sys
    
    proc = subprocess.Popen(['bash'])
    while True:
        buff = sys.stdin.readline()
        stdoutdata, stderrdata = proc.communicate(buff)
        if( stdoutdata ):
            print( stdoutdata )
        else:
            print('n')
            break
    

    Here 是我的类似问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-29
      • 2017-11-06
      • 2018-12-14
      相关资源
      最近更新 更多