Summary of several methods of executing shell commands in python

  • 2020-04-02 14:03:37
  • OfStack

A recent requirement was to execute shell commands on the page. The first thing that came to mind was os.system.


os.system('cat /proc/cpuinfo')

But finding a command printed on a page that executes with a result of 0 or 1, of course, is not enough.

Try the second option os.popen()


output = os.popen('cat /proc/cpuinfo')
print output.read()

What is returned through os.popen() is the object of the file read, which is read() operation to see the output of the execution. But cannot read the return value executed by the program.)

Try the third option, commands. Getstatusoutput (), a method to get the return value and output, which is very useful.


(status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
print status, output

An example given in Python Document,

>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>> commands.getoutput('ls /bin/ls')
'/bin/ls'
>>> commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'

The result of command execution can also be displayed on the final page based on the return value.


Related articles: