Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute shell command and retrieve stdout in Python [duplicate]

Tags:

python

shell

perl

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

like image 270
nowox Avatar asked Oct 29 '15 12:10

nowox


People also ask

How do you execute a shell command in Python and get output?

Get output from shell command using subprocessLaunch the shell command that we want to execute using subprocess. Popen function. The arguments to this command is the shell command as a list and specify output and error. The output from subprocess.

How do you execute a shell command in Python?

we are using the subprocess. Popen() method to execute the echo shell script using Python. You can give more arguments to the Popen function Object() , like shell=True, which will make the command run in a separate shell.


1 Answers

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("/"))
like image 106
Hooting Avatar answered Sep 28 '22 02:09

Hooting