python子进程无法读取airodumpnd mon0的输出

2024-06-01 06:30:06 发布

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

嗨,我正在尝试获取

airodump-ng mon0

其中mon0是我的无线接口的监控模式。 我想连续读取命令的输出,而不在某个时间间隔内终止进程

我的代码如下:

^{pr2}$

程序似乎卡在x=o_文件.read()。 请帮忙。在


Tags: 文件代码命令程序read间隔进程时间
1条回答
网友
1楼 · 发布于 2024-06-01 06:30:06

当同时设置stdout=subprocess.PIPEstderr=subprocess.PIPE时,存在死锁的风险(除非您使用communicate同时读取两个通道),因为如果进程写入标准错误,而您试图读取标准输出,则这两个都将永远阻塞。在

在您的例子中,您希望控制读取,因此communicate不是一个选项。我怀疑你只是想合并两个数据流,所以要改变:

stderr=subprocess.PIPE

通过

^{pr2}$

将标准错误重定向到标准输出并获取o_file.stdout中的所有output+error

顺便说一下:for i in [1, 2, 3, 4 ,5]:更像是“python”,比如:for _ in range(5):,因为您没有使用i,并且假设您要循环10000次:)

但是如果您的应用程序在所有情况下都不是一次打印行,这并不能解决您的问题,因为read()是阻塞的,您需要它在您想要的时候完全停止,所以我要:

  • 创建流程
  • 创建一个线程来读取循环中的行,并使用共享的布尔值来停止读取(因为如果输出缓冲区中有行,那么终止进程是不够的)
  • 等等
  • 将布尔值设置为True,并终止进程

像这样:

import subprocess
import time
import threading

stop_output = False

def f(p):
    global stop_output
    while True:
        l = p.stdout.readline()
        if not l or stop_output:
            break
        print(l.rstrip())   # or whatever you want to do with the line

airodump = subprocess.Popen(['airodump-ng','mon0'],stdin=subprocess.PIPE,
                      stdout=subprocess.PIPE,
                      stderr=subprocess.STDOUT,
                      universal_newlines=True
                    )
t = threading.Thread(target=f,args=(airodump,))
t.start()
time.sleep(10)
# kill the process and stop the display after 10 seconds whatever happens
airodump.terminate()
stop_output = True

相关问题 更多 >