Python子进程readline with timeou

2024-09-28 21:33:01 发布

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

你好,我有这样的问题,我需要执行一些命令并等待它的输出,但是在读取输出之前,我需要将\n写入管道。这是unitest,所以在某些情况下,我测试的命令不应答,我的测试用例在stdout.readline()处停止并等待smth。所以我的问题是,有没有可能设置一些东西,比如读线超时。在

cmd = ['some', 'list', 'of', 'commands']
fp = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
fp.stdin.write('\n')
fp.stdout.readline()
out, err = fp.communicate()

Tags: 命令cmdreadline管道stdinstdout情况测试用例
2条回答

等待响应不超过一秒钟:

from subprocess import Popen, PIPE

p = Popen(['command', 'the first argument', 'the second one', '3rd'],
          stdin=PIPE, stdout=PIPE, stderr=PIPE,
          universal_newlines=True)
out, err = p.communicate('\n', timeout=1) # write newline

通过3.2+子进程模块的http://pypi.python.org/pypi/subprocess32/后端口,python2.x上可以使用超时特性。见subprocess with timeout。在

对于使用线程的解决方案,信号报警,选择,iocp,twisted,或者只是一个临时文件,请参阅您的问题下面的相关帖子的链接。在

直接将输入传递给来自docs的通信https://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child.

示例:

cmd = ['some', 'list', 'of', 'commands']
fp = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = fp.communicate('\n')

相关问题 更多 >