将输入发送到python子进程而无需等待结果 [英] Send input to python subprocess without waiting for result

查看:132
本文介绍了将输入发送到python子进程而无需等待结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为一段代码编写一些基本测试,这些代码通常会通过stdin不断接受输入,直到给出特定的退出命令为止.

I'm trying to write some basic tests for a piece of code that normally accepts input endlessly through stdin until given a specific exit command.

我想检查程序是否在输入一些输入字符串后崩溃(经过一段时间处理后),但是似乎无法弄清楚如何发送数据并且不会卡住以等待输出不在乎.

I want to check if the program crashes on being given some input string (after some amount of time to account for processing), but can't seem to figure out how to send data and not be stuck waiting for output which I don't care about.

我当前的代码如下(使用cat作为程序示例):

My current code looks like this (using cat as an example of the program):

myproc = subprocess.Popen(['cat'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

myproc.communicate(input=inputdata.encode("utf-8"))
time.sleep(0.1)

if myproc.poll() != None:
    print("not running")
else:
    print("still running")

如何修改它以允许程序进行轮询而不是在communicate()调用后挂起?

How can I modify this to allow the program to proceed to the polling instead of hanging after the communicate() call?

推荐答案

您在此处使用错误的工具和communicate来等待程序结束.您应该只提供子流程的标准输入:

You are using the wrong tool here with communicate which waits for the end of the program. You should simply feed the standard input of the subprocess:

myproc = subprocess.Popen(['cat'], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE)
myproc.stdin.write(inputdata.encode("utf-8"))

time.sleep(0.1)

if myproc.poll() != None:
    print("not running")
else:
    print("still running")

但是请注意:您不能确定子进程结束之前输出管道中是否包含任何内容...

But beware: you cannot be sure that the output pipes will contain anything before the end of the subprocess...

这篇关于将输入发送到python子进程而无需等待结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆