Summary of several methods for executing shell commands in python, pythonshell
A recent requirement is to execute shell commands on the page. The first thing that comes to mind is OS. system,
Copy codeThe Code is as follows:
OS. system ('cat/proc/cpuinfo ')
However, the command execution result 0 or 1 printed on the page does not meet the requirements.
Try the second solution OS. popen ()
Copy codeThe Code is as follows:
Output = OS. popen ('cat/proc/cpuinfo ')
Print output. read ()
OS. popen () returns the object of file read. read () to view the output. However, the returned values of program execution cannot be read)
Try the third method commands. getstatusoutput () to obtain the return value and output, which is very easy to use.
Copy codeThe Code is as follows:
(Status, output) = commands. getstatusoutput ('cat/proc/cpuinfo ')
Print status, output
In Python Document,
Copy codeThe 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 command execution result can be displayed based on the returned value.
I want to execute shell commands multiple times using Python scripts
Cycle:
Import OS
For I in range (3 ):
OS. system ("date ");
I want to use python to write a web interface for simple execution of remote linux commands. The web interface should be able to enter and execute shell commands and scripts freely.
For remote operations, do not use the web interface or secure shell. If you want to write this python program, you need the subprocess and cgi in the standard library.