Summary of several methods for executing shell commands in python, pythonshell

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.