Python 捕获子流程的连续输出
我试图捕获airodump ng的输出,它有一个连续的输出,并处理每一行搜索字符串。但这不起作用。因此,我尝试使用具有相同类型输出的“htop”命令执行相同的操作,但仍然不起作用。 我正在用Python3.4和Python2.7尝试这一点,它们都是在ArchLinux和osx小牛上进行的。以下是代码(并非每次导入都是必需的,但无需考虑): 它给了我:Python 捕获子流程的连续输出,python,Python,我试图捕获airodump ng的输出,它有一个连续的输出,并处理每一行搜索字符串。但这不起作用。因此,我尝试使用具有相同类型输出的“htop”命令执行相同的操作,但仍然不起作用。 我正在用Python3.4和Python2.7尝试这一点,它们都是在ArchLinux和osx小牛上进行的。以下是代码(并非每次导入都是必需的,但无需考虑): 它给了我: Traceback (most recent call last): File "/Users/andrei/Dropbox/pyt
Traceback (most recent call last):
File "/Users/andrei/Dropbox/python/file_prova.py", line 8, in <module>
outs, errs = proc.communicate(timeout=3)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/subprocess.py", line 960, in communicate
stdout, stderr = self._communicate(input, endtime, timeout)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/subprocess.py", line 1618, in _communicate
self._check_timeout(endtime, orig_timeout)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/subprocess.py", line 986, in _check_timeout
raise TimeoutExpired(self.args, orig_timeout)
subprocess.TimeoutExpired: Command '['htop']' timed out after 3 seconds
它工作完美无瑕。使用htop。
但不适用于airodump ng。它在终端上打印输出,每1秒(while循环中的sleep())打印[不再打印数据],就像流要去别处一样
编辑2:
解决了的!问题是airodump ng将数据转储到stderr,而不是stdout。非常直截了当地从以下位置尝试ahah:D:
超时参数被传递给Popen.wait()。如果超时
过期时,子进程将被终止,然后再次等待。
TimeoutExpired异常将在子进程之后重新引发
已经终止
这似乎准确地描述了你所看到的行为。您需要学习使用
try
/进行异常处理,但
您的问题是什么?对我来说,这看起来像是3秒钟过去了,所以子流程模块引发了一个适当的异常。“3秒钟后超时”就是原因。您已指定3秒超时。
Traceback (most recent call last):
File "/Users/andrei/Dropbox/python/file_prova.py", line 8, in <module>
outs, errs = proc.communicate(timeout=3)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/subprocess.py", line 960, in communicate
stdout, stderr = self._communicate(input, endtime, timeout)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/subprocess.py", line 1618, in _communicate
self._check_timeout(endtime, orig_timeout)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/subprocess.py", line 986, in _check_timeout
raise TimeoutExpired(self.args, orig_timeout)
subprocess.TimeoutExpired: Command '['htop']' timed out after 3 seconds
from subprocess import Popen, PIPE
from time import sleep
from fcntl import fcntl, F_GETFL, F_SETFL
from os import O_NONBLOCK, read
# run the shell as a subprocess:
p = Popen(['htop'], stdout = PIPE)
# set the O_NONBLOCK flag of p.stdout file descriptor:
flags = fcntl(p.stdout, F_GETFL) # get current p.stdout flags
fcntl(p.stdout, F_SETFL, flags | O_NONBLOCK)
# let the shell output the result:
# get the output
while True:
sleep(1)
try:
print (read(p.stdout.fileno(), 1024).decode("utf-8")),
except OSError:
# the os throws an exception if there is no data
print ('[No more data]')
continue