12

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

6
  • What python version are you using? Commented Oct 29, 2015 at 12:23
  • Why not simply : os.system("cd ..") Commented Oct 29, 2015 at 12:35
  • 1
    OK fair enough, in which case you're up against questions like stackoverflow.com/q/89228/2088135 Commented Oct 29, 2015 at 12:35
  • 1
    Python and Perl are both high level scripting language but with different philosophies. Perl intends to let programmer do as less typing as possible, while Python forces neat structure to have easy to read code. You won't find expression unless condition either for same reason. Commented Oct 29, 2015 at 12:42
  • @TomFenech: I don't see how this question is related to the one you link to, which is about converting a path string Commented Oct 29, 2015 at 12:54

3 Answers 3

5

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("/"))
Sign up to request clarification or add additional context in comments.

Comments

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)

1 Comment

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).
0

You can try this

import os
print os.popen('ipconfig').read()
#'ipconfig' is an example of command

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.