如何从 python 脚本中的 运行 命令提取输出?
How to extract output from a running command in a python script?
是否可以从子进程中的命令 运行ning 中提取实时输出?
我想在我的脚本中使用名为 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
的 table 的数量(必须至少有一个 table 才不会中断):
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.before
和 child.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)
对我有用。
是否可以从子进程中的命令 运行ning 中提取实时输出?
我想在我的脚本中使用名为 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
的 table 的数量(必须至少有一个 table 才不会中断):
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.before
和 child.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)
对我有用。