arxoft
arxoft

Reputation: 1475

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?

Upvotes: 0

Views: 211

Answers (2)

orip
orip

Reputation: 75427

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

Or, if you're comfortable with basic shell splitting:

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

Be wary if sending user input directly to str.split or shlex.split and using the result with subprocess, it's too easy to bypass.

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

Upvotes: 3

Ahasanul Haque
Ahasanul Haque

Reputation: 11134

Try with shell = True:

import subprocess
subprocess.call('loginctl show-session -p Display -p Active c2', shell= True)

Output:

Display=:0
Active=yes

Upvotes: -1

Related Questions