Several ways that Python executes shell directives

Source: Internet
Author: User

1.os.system ()

Advantages: Simple, linux&widnows and other platforms are available, just to determine whether the return result is 0 or 1 to determine if the execution is successful.

Disadvantage: Unable to get return output.

Example:

Os.system (' ls ')


2.os.popen ()

Pros: can get output results

Disadvantage: Unable to get execution result, need to make judgment processing according to output result

Example:

Output = Os.popen (' ls ') print output.read ()


3.commands.getstatusoutput ()

Pros: Can simultaneously get execution results and return results

Cons: Windows platform does not support

Example:

Status, Output = Commands.getstatusoutput (' dir ') print status, output


4.subprocess. Popen ()

Advantage: can get execution result and return result simultaneously, support Linux&windows platform

Example:

p = subprocess. Popen (cmd, shell=true, stdin=subprocess. PIPE, Stdout=subprocess. PIPE, Stderr=subprocess. PIPE) msg = "For line in P.stdout.readlines ():    msg + = Linestatus = p.wait () output = msg





Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Several ways that Python executes shell directives

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.