将输入发送到python子进程而不等待resu

2024-06-07 10:53:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图为一段代码编写一些基本测试,这些代码通常通过stdin无休止地接受输入,直到给出特定的退出命令。在

我想检查程序是否在被赋予一些输入字符串时崩溃(经过一段时间的处理),但似乎无法确定如何发送数据,而不是被困在等待我不关心的输出。在

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

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()调用后挂起?在


Tags: 字符串代码命令程序stdinrunning发送数据cat
3条回答

所以我想我明白你想要什么。如果你知道一个现有的命令会使你的程序崩溃,你可以使用'子进程.Popen.wait(),但它将返回输出消息的元组以及与之相关的错误(如果有)。在

然后可以记录错误并在try异常语句中捕获它。在

这在我处理子流程时非常有用: https://docs.python.org/3/library/asyncio-subprocess.html

您可以在^{}函数中设置超时。超时后,进程仍在运行,我认为,但你必须测试它,你仍然可以发送输入与通信。在

从文件中:

If the process does not terminate after timeout seconds, a TimeoutExpired exception will be raised. Catching this exception and retrying communication will not lose any output.

The child process is not killed if the timeout expires, so in order to cleanup properly a well-behaved application should kill the child process and finish communication:

您在这里使用了错误的工具communicate,它等待程序结束。您只需输入子流程的标准输入:

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")

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

相关问题 更多 >

    热门问题