Python Execution system command: Os.system,os.popen,commands

Source: Internet
Author: User

When writing scripts, the system commands are often executed directly.

First, the Os.system () command is used.

Import Osos.system ("cat/etc/hosts")

However, this method does not get the output and return values.

Two. Then I used the Os.popen () command

Import= Os.popen ("cat/etc/hosts")print Output.read ()

The file read object is returned through Os.popen, so you can see the output directly by Output.read () operation if you want to get the content.

This method also does not get the return value

Three. Commands command

Import= Commands.getstatusoutput ("cat/etc/hosts")Print  Type (status), statusprint type (output), output

You can get the return status and return value here.

Take a look at some examples: (I use the Ipython)

In [1]: Import commands

In [3]: Commands.getstatusoutput ("ls/data/")
OUT[3]: (0, ' dictionary\nhotwords\nlogs\nwordsegment ')

In [4]: Commands.getstatusoutput ("cat/etc/")
OUT[4]: (+, ' Cat:/etc/: is a directory ')

In [6]: Commands.getoutput ("ls/etc/hosts")
OUT[6]: '/etc/hosts '

In [9]: Commands.getstatus ("/BIN/LN")

OUT[9]: '-rwxr-xr-x 1 root root 56072 Mar 2014/bin/ln '

Python Execution system command: Os.system,os.popen,commands

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.