7

In Perl, if I want to execute a shell command such as foo, I'll do this:

#!/usr/bin/perl
$stdout = `foo`

In Python I found this very complex solution:

#!/usr/bin/python
import subprocess
p = subprocess.Popen('foo', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = p.stdout.readlines()
retval = p.wait()

Is there any better solution ?

Notice that I don't want to use call or os.system. I would like to place stdout on a variable

AMACB
  • 1,232
  • 1
  • 16
  • 24
nowox
  • 19,233
  • 18
  • 91
  • 202

3 Answers3

4

An easy way is to use sh package. some examples:

import sh
print(sh.ls("/"))

# same thing as above
from sh import ls
print(ls("/"))
Hooting
  • 1,463
  • 10
  • 19
0

Read more of the subprocess docs. It has a lot of simplifying helper functions:

output = subprocess.check_output('foo', shell=True, stderr=subprocess.STDOUT)
ShadowRanger
  • 108,619
  • 9
  • 124
  • 184
  • Also, you probably don't need `shell=True` in most cases and should avoid it for performance and security reasons in general (similarly, in Perl, it's best to avoid backticks for the same reason, in favor of solutions like 3+ arg `open` and reading the resulting file handle). – ShadowRanger Oct 29 '15 at 12:47
0

You can try this

import os
print os.popen('ipconfig').read()
#'ipconfig' is an example of command
H Neb
  • 25
  • 5