Python Call Shell

Source: Internet
Author: User

Today, I learned that Python calls the shell through a child process, feeling that the tutorial is too complicated, there are some fundamentally useless features, such as redirecting input and output, the shell itself is supported, there is no need to use the Python API. Decide yourself to summarize under.

In fact, there are only two kinds:

The first is a simple call, in which case the parent process waits for the child process to complete and the return value is the exit information, as an example:

# Import sub-process package Import subprocess # simple call, can write multiple shell statements, separated by semicolons, you can redirect the shell-side output to text for Python to read, R returns 0 instructions to run the normal R=subprocess.call ("CD. /;ls|wc-l >r.txt 2>&1", Shell=true)

The second is a full call, using the Popen class, and the previous simple call is actually encapsulated with Popen. Popen The default parent process does not wait for the child process to complete, but can be set through parameters, for example:

Child=subprocess. Popen ("ping-c 5 www.baidu.com", shell=True)print'Parent Process'

When using Popen, you can add the Child.wait () method if you want the parent process to wait for the child process to finish executing.

Some other methods/properties are listed below

Child.pid #子进程pid

Child.poll () #检查子进程状态

Child.kill ()/child.terminate () #终止子进程

Child.send_signal () #向子进程发送信号

Python Call Shell

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.