[Tutor] System output into variable?
Peter Otten
__peter__ at web.de
Thu Apr 3 16:21:35 CEST 2014
leam hall wrote:
> I've been trying to so a simple "run a command and put the output into a
> variable". Using Python 2.4 and 2.6 with no option to move. The go is to
> do something like this:
>
> my_var = "ls -l my_file"
>
> So far the best I've seen is:
>
> line = os.popen('ls -l my_file', stdout=subprocess.PIPE, shell=True)
> (out, err) = line.communicate()
>
> With no way to make 'my_file' a variable.
>
> I've got to be missing something, but I'm not sure what. Python has always
> impressed me a a language without a lot of hoops to go through.
In Python 2.7 and above there is subprocess.check_output():
>>> import subprocess
>>> filename = "my_file"
>>> my_var = subprocess.check_output(["ls", "-l", filename])
>>> my_var
'-rw-r--r-- 1 nn nn 0 Apr 3 16:14 my_file\n'
Have a look at its source code, it should be possible to backport the function:
>>> import inspect
def check_output(*popenargs, **kwargs):
r"""Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example:
>>> check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.
>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
'ls: non_existent_file: No such file or directory\n'
"""
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = Popen(stdout=PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise CalledProcessError(retcode, cmd, output=output)
return output
More information about the Tutor
mailing list