Home > Backend Development > Python Tutorial > Detailed explanation of three methods of executing shell commands in python

Detailed explanation of three methods of executing shell commands in python

高洛峰
Release: 2018-05-12 16:09:48
Original
2259 people have browsed it

Recently there is a need to execute shell commands on the page.

The first one is os.system.

The code is as follows:

os.system('cat /proc/cpuinfo')
Copy after login

But I found that the page printed The command execution result is 0 or 1, which of course does not meet the requirements.

Try the second solution os.popen()

The code is as follows:

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

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

Try the third solution commands.getstatusoutput(). You can get the return value and output in one method, which is very easy to use.

The code is as follows:

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

An example given in the Python Document,

The code is as follows:

>>> 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'
Copy after login


The above is the detailed content of Detailed explanation of three methods of executing shell commands in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template