Several methods of executing shell commands in Python summary _python

Source: Internet
Author: User
Tags in python

A recent requirement is to execute the shell command on the page, the first thought is Os.system,

Copy Code code as follows:

Os.system (' Cat/proc/cpuinfo ')

But the results of a printed command on the page 0 or 1, of course, do not meet the requirements.

Try the second scenario Os.popen ()

Copy Code code as follows:

Output = Os.popen (' Cat/proc/cpuinfo ')
Print Output.read ()

A file read object is returned by Os.popen () that reads the read () action to see the output being executed. However, the return value that the program performs cannot be read)

Try a third scheme commands.getstatusoutput () a method can get to the return value and output, very useful.

Copy Code code as follows:

(status, Output) = Commands.getstatusoutput (' Cat/proc/cpuinfo ')
Print status, output

An example given in the Python Document,
Copy Code code 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 1994/bin/ls '

The results of the command execution can also be displayed on the last page based on the return value.

Related Article

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.