Score:0

Running systemctl in Python script

cn flag

I'm trying to get the status of a few systemd services in Python, but I keep getting the error FileNotFoundError: [Errno 2] No such file or directory: 'systemctl show -p ActiveState --value abc'

I'm running Ubuntu 20.04, as the user user. The abc.service file is in /etc/systemd/system/, details below:

-rw-rw-r--  1 root root 1542 Aug  5 17:31  abc.service

The script is

import subprocess
status = subprocess.check_output("systemctl show -p ActiveState --value abc")
print(status)

However, if I run the systemctl command directly, I can get the status active. I've tried with sudo in the script, and I get the same error.

On a related note, I thought I would have to run the command using sudo eventually, but I'm actually running the command as part of my Airflow dag (i.e. not as a separate script where I can do sudo python3 myscript.py). Is there a way to do this?

ajgringo619 avatar
de flag
I think this will help: https://stackoverflow.com/questions/2449250/any-way-to-assign-terminal-output-to-variable-with-python#2449301
Score:0
cn flag

I was careless, and did not include shell=True in my subprocess. Once I added it, it runs successfully.

status = subprocess.check_output("systemctl show -p ActiveState --value abc", shell=True)
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.