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
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.
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.
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("/"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With