gpt4 book ai didi

python - 解析预期输出

转载 作者:太空狗 更新时间:2023-10-30 01:29:19 25 4
gpt4 key购买 nike

我正在尝试实时解析 block 缓冲程序的输出,这意味着在进程结束之前输出不可用。我需要的只是逐行解析、过滤和管理输出中的数据,因为它可能会运行数小时。

我尝试使用 subprocess.Popen() 捕获输出,但是,正如您可能猜到的那样,Popen 无法管理这种行为,它会一直缓冲直到进程结束。

from subprocess import Popen, PIPE

p = Popen("my noisy stuff ", shell=True, stdout=PIPE, stderr=PIPE)
for line in p.stdout.readlines():
#parsing text and getting data

所以我找到了 pexpect,它实时打印输出,因为它将标准输出视为一个文件,或者我什至可以做一个肮脏的把戏打印出一个文件并在函数外解析它。但是好吧,它太脏了,即使对我来说也是如此 ;)

import pexpect
import sys

pexpect.run("my noisy stuff", logfile=sys.stdout)

但我想这应该是一种更好的 pythonic 方式来做到这一点,只需像子进程一样管理标准输出。 Popen 确实如此。我该怎么做?

编辑:

运行 J.F. 提案:

这是一次故意错误的审核,大约需要 25 秒。停止。

from subprocess import Popen, PIPE

command = "bully mon0 -e ESSID -c 8 -b aa:bb:cc:dd:ee:00 -v 2"

p = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)

for line in iter(p.stdout.readline, b''):
print "inside loop"
print line

print "outside loop"
p.stdout.close()
p.wait()


#$ sudo python SCRIPT.py
### <= 25 secs later......
# inside loop
#[!] Bully v1.0-21 - WPS vulnerability assessment utility

#inside loop
#[!] Using 'ee:cc:bb:aa:bb:ee' for the source MAC address

#inside loop
#[X] Unable to get a beacon from the AP, possible causes are

#inside loop
#[.] an invalid --bssid or -essid was provided,

#inside loop
#[.] the access point isn't on channel '8',

#inside loop
#[.] you aren't close enough to the access point.

#outside loop

改为使用此方法:编辑:由于输出中的大量延迟和超时,我不得不修复 child ,并添加了一些技巧,所以最终代码如下所示

import pexpect

child = pexpect.spawn(command)
child.maxsize = 1 #Turns off buffering
child.timeout = 50 # default is 30, insufficient for me. Crashes were due to this param.
for line in child:
print line,

child.close()

返回相同的输出,但它实时打印行。所以...解决了谢谢@J.F.塞巴斯蒂安

最佳答案

.readlines() 读取所有行。难怪在子进程结束之前您看不到任何 输出。您可以使用 .readline() 而不是在子进程刷新其标准输出缓冲区后立即逐行读取:

from subprocess import Popen, PIPE

p = Popen("my noisy stuff", stdout=PIPE, bufsize=1)
for line in iter(p.stdout.readline, b''):
# process line
..
p.stdout.close()
p.wait()

如果您已经有了 pexpect,那么您可以使用它来解决 block 缓冲问题:

import pexpect

child = pexpect.spawn("my noisy stuff", timeout=None)
for line in child:
# process line
..
child.close()

另见 stdbuf, pty -based solutions来 self 在评论中链接的问题。

关于python - 解析预期输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20182827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com