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')
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()
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
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'
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!