python - Python - 脚本挂在 open() 函数上
问题描述
我有一个 Python 脚本,它首先杀死所有hostapd
进程,然后启动一个新进程。我想捕获hostapd
start 命令的输出以确定它是否返回AP-ENABLED
,或者AP-DISABLED
我决定将它写入一个临时文件然后读取它。
但是open()
无限期挂起,或者直到我使用 ctrl-c; 该程序没有退出,而是吐出我期望的输出:
Line #0: Configuration file: /etc/hostapd/hostapd.conf
Line #1: Failed to create interface mon.wlan0: -95 (Operation not supported)
Line #2: wlan0: interface state UNINITIALIZED->COUNTRY_UPDATE
Line #3: wlan0: Could not connect to kernel driver
Line #4: Using interface wlan0 with hwaddr b8:27:eb:35:34:de and ssid "Coriolis"
Line #5: random: Only 6/20 bytes of strong random data available from /dev/random
Line #6: random: Not enough entropy pool available for secure operations
Line #7: WPA: Not enough entropy in random pool for secure operations - update keys later when the first station connects
Line #8: wlan0: interface state COUNTRY_UPDATE->ENABLED
Line #9: wlan0: AP-ENABLED
代码:
import subprocess
import os
import sys
def start_hostapd():
# kill any existing hostapd process
subprocess.call(['killall', 'hostapd'])
# start new hostapd process
os.system('hostapd /etc/hostapd/hostapd.conf > ./hostapd.log')
# capture the output
line_num = 0
with open('hostapd.log', 'r') as file:
for line in file:
print('\nLine #{}: {}'.format(line_num, line))
line_num += 1
# sys.stdout.flush()
if __name__ == '__main__':
start_hostapd()
我尝试添加sys.stdout.flush()
但无济于事。
解决方案
好的,所以我会解释你为什么你在这里有问题。
守护进程也是如此hostapd
(查看名称中的最后一个d,大多数 linux 守护进程都有它)。
所以你试图用os.system
. 在文档中,我检查了该函数是否生成并返回进程返回代码。但是要获得返回码,os.system
必须等待守护进程完成。所以这就是它挂在这里的原因。
作为解决方案。我建议使用一些无等待功能来生成守护进程,例如os.spawn
使用os.P_NOWAIT
标志。
推荐阅读
- r - h2o.distance 和 dist 函数之间的差异
- spyder - Spyder 不处理相对进口
- python - 想要开始/暂停视频时,我应该如何正确使用 cv2.waitKey?
- sdl-2 - SDL2 - 结合前后缓冲区?
- python-3.x - 特金特
事件绑定在 python 脚本中不起作用 - python - Replace_Downloads.py 中的 Python 异常 IndexError
- javascript - 将文本添加到标记(功能)
- sql - Postgresql分组错误:用作表达式的子查询返回多行
- php - PHP - 解析大型 XML URL
- c - 如何在c中将文本文件拆分为多个部分