简体   繁体   中英

How can i read the output from an executed shell command?

I've read numerous questions about this subject, and even 2 which have accepted answers, which then have in the comment the same issue as i'm experiencing.

So what I want to do is catch the output of this command (which works in the command line)

 sudo /usr/bin/atq

in my Python program.

This is my code (which is an accepted answer in another question)

from subprocess import Popen, PIPE

output = Popen(['sudo /usr/bin/atq', ''], stdout=PIPE)
print output.stdout.read()

and this is the result:

  File "try2.py", line 3, in <module>
    output = Popen(['sudo /usr/bin/atq', ''], stdout=PIPE)
  File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1259, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

Why oh why is this the result (in Python 2.7, on a debian Raspbarry Wheezy install)?

I believe all you need to do is change,

output = Popen(['sudo /usr/bin/atq'], stdout=PIPE)

to

output = Popen(['sudo', '/usr/bin/atq'], stdout=PIPE)

I get the same error when I include multiple arguments as a single string in the args list.

The arguments to Popen need to be a list, you could use shlex to handle this automatically for you

import shlex
args = shlex.split('sudo /usr/bin/atq')
print args

produces

['sudo', '/usr/bin/atq']

which you can then pass to Popen . Then you'll need to communicate with the process you've created. Have a go with .communicate() (note arguments to Popen here are a list!) ie

prc = Popen(['sudo', '/usr/bin/atq'], stdout=PIPE, stderr=PIPE)
output, stderr = prc.communicate()
print output

Popen returns the subprocess handle, which you need to communicate with to get the output. Note - adding stderr=PIPE will give you access to STDERR as well as STDOUT .

You can use subprocess.check_output() :

subprocess.check_output(['sudo', '/usr/bin/atq'])

example:

In [11]: print subprocess.check_output(["ps"])
  PID TTY          TIME CMD
 4547 pts/0    00:00:00 bash
 4599 pts/0    00:00:00 python
 4607 pts/0    00:00:00 python
 4697 pts/0    00:00:00 ps

help() :

In [12]: subprocess.check_output?
Type:       function
String Form:<function check_output at 0xa0e9a74>
File:       /usr/lib/python2.7/subprocess.py
Definition: subprocess.check_output(*popenargs, **kwargs)
Docstring:
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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM