I want to create a function that will return output of a shell, I have something like this:
def shell_exec(code):
buff = StringIO.StringIO()
subprocess.call(code, shell=True, stdout=buff)
return buff.getvalue()
but got error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in shell_exec
File "/usr/lib/python2.7/subprocess.py", line 524, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 703, in __init__
errread, errwrite) = self._get_handles(stdin, stdout, stderr)
File "/usr/lib/python2.7/subprocess.py", line 1115, in _get_handles
c2pwrite = stdout.fileno()
AttributeError: StringIO instance has no attribute 'fileno'
Use subprocess.check_output
. It returns command output.
def shell_exec(code):
try:
return subprocess.check_output(code, shell=True)
except subprocess.CalledProcessError as e:
return e.output
BTW, valid values for stdin
, stdout
, stderr
are PIPE
, DEVNULL
, an existing file descriptor (a positive integer), an existing file object, and None
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.