Python module--subprocess

Source: Internet
Author: User

Tag: Create a standard input containing Shel user plain End Try Arm

subprocess Module

The subprocess module is used to help us execute some system commands in Python code, and when executing a python program, the module creates a child process to run the external program.

The module has several methods, as follows:

    • Subprocess.call ()
      The result of the direct Print System command, if executed successfully, returns a status code of 0, otherwise 1, for example:

#执行成功import subprocessCALL1 = Subprocess.call (' ping 127.0.0.1-n 1 ', shell=true) print ("returncode:%d"%call1)

Printing results are:

Ping 127.0.0.1 has 32 bytes of data: Reply from 127.0.0.1: Byte =32 time <1ms ttl=128127.0.0.1 Ping statistics: packet: Sent = 1, received = 1, missing = 0 (0% lost), estimated time of round trip (in milliseconds): shortest = 0ms, longest = 0ms, average = 0msreturncode:0
#执行失败CALL2 = Subprocess.call (' ping 1.1.1.2-n 1 ', shell=true) print ("returncode:%d"%call2)

Printing results are:

Pinging 1.1.1.2 with 32 bytes of data: Request timed out. Ping Statistics for 1.1.1.2: packet: Sent = 1, received = 0, lost = 1 (100% missing), returncode:1


    • Subprocess.check_call ()
      The result of the direct Print System command is used in the same way as Subprocess.call (), except that the function detects the return status code and, if 1, throws subprocess. Calledprocesserror errors, such as:

Import subprocess# Execution succeeded # check_call1 = Subprocess.check_call (' ping 127.0.0.1-n 1 ', shell=true) # print (CHECK_CALL1) # Execution failed check_call2 = Subprocess.check_call (' ping 1.1.1.2-n 1 ', shell=true) print (CHECK_CALL2)

Printing results are:

Pinging 1.1.1.2 with 32 bytes of data: Request timed out. Ping Statistics for 1.1.1.2: packet: Sent = 1, received = 0, lost = 1 (100% lost), Traceback (most recent call last): File "C:/users/administr ator/pycharmprojects/first/subprocess/check_call.py ", line 7, in <module> check_call2 = Subprocess.check_call (' Ping 1.1.1.2-n 1 ', shell=true) File "C:\Python3.6\lib\subprocess.py", line 291, in Check_call raise Calledprocesserror (Retcode, cmd) subprocess. Calledprocesserror:command ' ping 1.1.1.2-n 1 ' returned Non-zero exit status 1.

Can be combined with try...expect ... Statement to do exception handling.


    • Subprocess.check_output ()

does not print the result of the system command directly, returning an object of type bytes that contains the execution result of the system command and throws subprocess if the execution fails. Calledprocesserror errors, such as:

Import subprocess# performed successfully check_output1 = Subprocess.check_output (' ping 127.0.0.1-n 1 ', shell=true) print (Type (check_ OUTPUT1)) print (str (CHECK_OUTPUT1, ' GBK '))

Printing results are:

<class ' bytes ' > is pinging 127.0.0.1 with 32 bytes of data: Reply from 127.0.0.1: bytes =32 time <1ms ttl=128127.0.0.1 Ping statistics: Packets: Sent = 1, received = 1, lost = 0 (0% missing), estimated time of round trip (in milliseconds): shortest = 0ms, longest = 0ms, average = 0ms


    • Subprocess. Popen ()

The above functions are encapsulated in Popen (), and the main process waits for the child process to complete, and the child process created by Popen () is not waiting, which is equivalent to executing asynchronously.

1.Popen () Creates an object that has several methods that can be personalized for a child process, such as the following:

Import Subprocessimport timetime.clock () POPEN1 = subprocess. Popen (' ping 127.0.0.1-n ', shell=true) print (POPEN1) print (Time.clock ())

Printing results are:

<subprocess. Popen object at 0x02230810>0.06108553745727746# from the time, the main program will soon be over.

The object methods created by Popen () include:

Popen1.poll () # Check child process Status Popen1.kill () # terminating child process Popen1.terminate () # terminating child process popen1.send_signal () # Send signal to subprocess PID attribute contains PID number of child process

2.subprocess. Popen () Another commonly used feature is text flow control, which corresponds to "standard input", "standard output", and "standard error", respectively:

POPEN1.stdinPOPEN1.stdoutPOPEN1.stderr

Subprocess. Pipe (provides a buffer for text flow) as a conduit that can be used to connect standard output and standard input, for example:

POPEN2 = subprocess. Popen (' ping 127.0.0.1-n 1 ', shell=true,stdout=subprocess. PIPE) STDOUT2 = popen2.stdout# print (str (stdout2.read (), ' GBK ')) POPEN3 = subprocess. Popen (' findstr packet ', shell=true,stdin=stdout2,stdout=subprocess. PIPE) STDOUT3 = Popen3.stdoutprint (str (stdout3.read (), ' GBK '))

The result of the execution is:

Packet: Sent = 1, received = 1, lost = 0 (0% missing),



Python module--subprocess

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.