0

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?

arxoft
  • 1,385
  • 3
  • 17
  • 34

2 Answers2

3
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.

Community
  • 1
  • 1
orip
  • 73,323
  • 21
  • 116
  • 148
  • `subprocess.call(cmd.split())` would this also work for some command like `git commit -m "This is a message"`? Note the use of spaces. – arxoft May 01 '16 at 11:17
  • 1
    @aceph: don't use `.split()` or `shlex.split()` unless the input is a string literal here—both are easily fooled. `.split()` could be used to make the line less "noisy", to make the command more readable. If the input is not a constant then use a list: *one list item per the command-line argument* – jfs May 01 '16 at 11:46
  • @aceph - no, in your case it won't, but as @J.F Sebastian mentioned `shlex.split` will. Never trust it with external input, though. Edited the answer, shlex.split is much better than str.split here (TIL) – orip May 01 '16 at 12:51
-1

Try with shell = True:

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

Output:

Display=:0
Active=yes
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
  • Upvoted because this is valid for quick&dirty cases (e.g replacing a shell script) but you should be aware of the implementation and the risks: official docs - https://docs.python.org/2/library/subprocess.html#frequently-used-arguments, SO answer - http://stackoverflow.com/a/3172488/37020 – orip May 01 '16 at 10:55