簡體   English   中英

如何從python腳本中的運行命令中提取輸出?

[英]How to extract output from a running command in a python script?

是否可以從子進程中運行的命令中提取實時輸出?

我想在我的腳本中使用名為 wifite ( https://github.com/derv82/wifite ) 的程序的輸出。 Wifite 應該在我的腳本中的一個子進程中運行 - 在特定時間 wifite 將輸出它的掃描結果並每秒更新它們(或接近的時間)。 我想在運行時讓這行輸出顯示在我的 Raspberry Pi Adafruit LCD 上。

所以我想做這樣的事情:

wifite_scan = subprocess.Popen('./wifite.py', shell=True, stdout =PIPE)
wfite_scanOut= wifite_scan.communicate()
lcd.message(wifite_scanOut)

但這行不通(如果我錯了,請糾正我)現場直播。

...要在我的液晶顯示器上顯示此輸出的最后一行:


1  Example1               7  WPA2  58db   wps 
2  Example2               6  WPA2  47db    no 
3  Example4               7  WPA2  47db    no 
4  Example5               1  WPA2  31db    no 

[0:00:11] scanning wireless networks. 4 targets and 0 clients found

此輸出每 5 秒更新一次,並且僅在控制台中發布具有新值的相同輸出。 所以我需要一種方法來每 5 秒獲取一次變量中的最后一行。

實現實時輸出到 lcd 的最佳方法是什么?

試過pexpect嗎? 我已經成功地將它與各種軟件一起使用。

示例 - 使用 mysql 客戶端計算test表的數量(必須至少有一張表不會損壞):

child = pexpect.spawn('mysql')
child.expect('mysql>')
child.sendline('use test; show tables;')
child.expect('(\d+) row.* in set \(.*\)')
count_tables = child.match.groups()[0]

之后調用expect(expr) ,你可以檢查緩沖區的內容child.beforechild.buffer

我不確定它是否適合您的問題(因為我不知道下標的輸出是什么樣的),但這可能是一個解決方案:

import subprocess

wifite_scan = subprocess.Popen('wifite.py', shell=True, stdout=subprocess.PIPE)
while True:
    output = wifite_scan.stdout.readline()
    if output == '':
        # end of stream
        print("End of Stream")
        break
    if output is not None:
        # here you could do whatever you want with the output.
        print("Output Read: "+output)

我用一個生成一些輸出的簡單文件嘗試了上面的腳本:

# wifite.py
import time

for i in range(10):
    print(i)
    time.sleep(1)

為我工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM