Python - 脚本卡在 open() 函数上

标签 python raspberry-pi subprocess sys hostapd

我有一个 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.spawnos.P_NOWAIT旗帜。

关于Python - 脚本卡在 open() 函数上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52629543/

相关文章:

java - 如何让 tomcat 从目录自动部署 WAR 文件,但仍使用原始 appBase 目录

cmake - 交叉编译并链接到 sysroot 中的库 - 怎么了?

python - 为什么 subprocess.Popen 参数长度限制小于操作系统报告的长度?

python - 为什么 multiprocessing.sharedctypes 赋值这么慢?

python - 获取可变数量组的正则表达式

javascript - 防止我的 node.js 应用程序被操作系统杀死

相当于在 Windows 中双击的 Python 子进程模块

python - y_true 和 y_pred 具有不同数量的输出 (10!=1)

python - 如何从同一个类的页面中的两个表中提取数据?

python 检查输出查找命令不起作用