【问题标题】:Communicate multiple times with a subprocess in Python在 Python 中与子进程多次通信
【发布时间】:2017-02-15 09:08:05
【问题描述】:

这个问题不是重复的

Communicate multiple times with a process without breaking the pipe?

该问题已解决,因为它的用例允许一起发送输入,但如果您的程序是交互式的(如此处的用例所示),则情况并非如此。


文件subprocess.Popen 说:

communicate(input=None)
    Interact with process: Send data to stdin.  Read data from stdout
    and stderr, until end-of-file is reached.  Wait for process to
    terminate.  ...

是否可以在子进程终止之前与其进行多次通信,例如与终端或网络套接字?

例如,如果子进程是bc,则父进程可能希望根据需要向其发送不同的输入进行计算。由于发送到bc 的输入可能取决于用户输入,因此不可能一次发送所有输入。

【问题讨论】:

    标签: python ipc


    【解决方案1】:

    基本上Non-blocking read on a subprocess.PIPE in python

    通过fnctl 将 proc 管道(proc.stdout、proc.stdin、...)设置为非阻塞模式,然后直接写入/读取它们。

    您可能希望使用 epoll 或通过 selectio 模块进行选择以提高效率。

    【讨论】:

      【解决方案2】:

      事实证明这并不难:

      proc = subprocess.Popen(['bc'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
      os.write(proc.stdin.fileno(), b'100+200\n')
      print(os.read(proc.stdout.fileno(), 4096))
      

      【讨论】:

        猜你喜欢
        • 2011-03-28
        • 2012-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-26
        • 2015-02-19
        • 1970-01-01
        • 2017-07-08
        相关资源
        最近更新 更多