aceph aceph - 5 months ago 7
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:


In Python, I do it this way:

import subprocess['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['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'

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