[Tutor] commands.getoutput equivalent in subprocess

Peter Otten __peter__ at web.de
Sun Mar 18 13:23:38 CET 2012

Pete O'Connell wrote:

> Hello I print a lot of values at work using grep and need to be
> constantly opening a shell window to do this (rather than staying
> within my main program which is Nuke by the Foundry). Is there a
> simple equilavent to commands.getoutput that is more up to date (I
> would assume within the subprocess module)? It sounds like the
> commands module will be phased out soonish. I am using Python 2.6
> Here is the kind of thing I would like to do in subprocess
> import commands
> output = commands.getoutput("echo Hello World!")
> print output

Here's the equivalent for Python 3:

>>> import subprocess
>>> output = subprocess.getoutput("echo Hello World!")
>>> print(output)
Hello World!


For invoking external programs you should still consider something more 
involved like

>>> p = subprocess.Popen(["grep", "^def\s", 
"/usr/lib/python3.2/subprocess.py"], stdout=subprocess.PIPE)
>>> print(p.communicate()[0].decode("utf-8"))
def _cleanup():
def _eintr_retry_call(func, *args):
def call(*popenargs, **kwargs):
def check_call(*popenargs, **kwargs):
def check_output(*popenargs, **kwargs):
def list2cmdline(seq):
def getstatusoutput(cmd):
def getoutput(cmd):
def _demo_posix():
def _demo_windows():

More information about the Tutor mailing list