Python - script hangs on open() function

1.9k views Asked by At

I have a Python script that first kills all hostapd processes then starts a fresh one. I want to capture the output of the hostapd start command to determine if it returns AP-ENABLED or AP-DISABLED so I decided to write it to a temporary file then read it.

However open() hangs indefinitely, or until I use ctrl-c; the program does not exit, but instead pukes out the output I expected:

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

Code:

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()

I tried adding sys.stdout.flush() but to no avail.

2

There are 2 answers

2
Take_Care_ On BEST ANSWER

OK so I will explain You why You have problem here.

So hostapd is daemon process (Look at the last d in the name, most linux daemons have it).

So You are trying to start this daemon with the os.system. In the documentation I have checked that this function spawns and returns the process return code. But to get the return code the os.system must wait for the daemon to finish. So that's why it hangs here.

As a solution. I suggest spawning the daemon with some no waiting function, like os.spawn with the os.P_NOWAIT flag.

0
Andrew On

Have you tried to add the flush = True to the print function, maybe it works like that