Python sub-process

Source: Internet
Author: User

Recently, a small tool needs to use the python word process. After reading the python API, the subprocess module can be implemented, and it is quite simple.

To implement a simple self-process, you only need

Import sys, OS, subprocess <br/> P = subprocess. popen (["ls", "-l"], shell = false, stdin = none, stdout = none, stderr = none) <br/> Print p. PID <br/> Print p. returncode 

In this case, the PID will be the ID of the sub-process. If the sub-process is launched normally, the returncode will be none.

 

You can also use the followingCodeCreate a sub-process

Import sys, OS, subprocess <br/> retcode = subprocess. call (["ls", "-l"], shell = false, stdin = none, stdout = none, stderr = none) <br/> Print retcode 

 

At this time, if the sub-process is launched normally, the retcode will be 0.

 

In addition, if you do not want to output the printed information of the created sub-process, you can set stdout and stderr in the method parameters to subprocess. pipe.

 

The following is a small example: create a sub-process P1, and then create a sub-process p2 to end P1 execution.

Import sys, OS, subprocess <br/> P1 = subprocess. popen (["Sleep", "60"], shell = false, stdin = none, stdout = none, stderr = none) <br/> Print p1.pid <br/> Print p1.returncode <br/> P2 = subprocess. popen (["kill", STR (p1.pid)], shell = false, stdin = none, stdout = none, stderr = none) <br/> Print p2.pid <br/> Print p2.returncode 

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.