aceph aceph - 7 months ago 10
Python Question

How to subprocess this CLI command

I want to get output of this shell command using Python:

loginctl show-session -p Display -p Active c2


Output is:

Display=:0
Active=yes


In Python, I do it this way:

import subprocess
subprocess.call(['loginctl', 'show-session -p Display -p Active c2'])


I get this error:

Unknown operation show-session -p Display -p Active c2


What could be cause?

Answer
subprocess.call(['loginctl', 'show-session', '-p', 'Display', '-p', 'Active', 'c2'])

Or, if you're comfortable with spaces being a good delimiter (which breaks surprisingly often but works for simple cases):

cmd = 'loginctl show-session -p Display -p Active c2'
subprocess.call(cmd.split())

Adding shell = True should also work but with quite a few side effects, see the official docs and this StackOverflow answer.