Search code examples
subprocesspisystemctlhostapd

Subprocess check_output of 'systemctl status hostapd' always returning exit code 3


I am on a raspberry 4B with headless raspbian v10 (buster). I am trying to get the response from the sudo systemctl status hostapd command using subprocess.check_output. Simply running sudo systemctl status hostapd in the raspi terminal works just fine and I get what I want to see:

  sudo systemctl status hostapd
● hostapd.service - Advanced IEEE 802.11 AP and IEEE 802.1X/WPA/WPA2/EAP Authenticator
   Loaded: loaded (/lib/systemd/system/hostapd.service; enabled; vendor preset: enabled)
   Active: inactive (dead)

However, when I run the code:
response = subprocess.check_output(['sudo systemctl status hostapd'], shell=True).decode('utf-8')
I get the error message:
Error: Command 'systemctl status hostapd.service' returned non-zero exit status 3.

Adding stderr=subprocess.STDOUT to the argument list does not provide more information.

Can someone tell me why the error is raised and what it means?


Solution

  • The correct use of check_output is as follows:

    subprocess.check_output(['systemctl','status','hostapd']).decode('utf-8')
    

    Each argument in the command is part of an array and not the whole command.

    Also, I suggest removing "sudo" from the command, and just run your python script with sudo.