Python Basics-4.13 subprocess Module

Source: Internet
Author: User
Tags stdin string format

We often need to execute a system command or script through Python, the system's shell command is independent of your Python process, each execution of a command, is to initiate a new process, Modules that call system commands or scripts through Python have os.system in Python2,

In [3]: Os.system ('uname-a'#127-ubuntu SMP Mon Dec 12:16:42 UTC x86_64 x86_64 x86_64 gnu/linuxout[3]: 0  #  command execution succeeded

What is the implementation principle of this command? (In the video, explain the problem of inter-process communication ...)

In addition to Os.system can call system commands,, COMMANDS,POPEN2, etc. can also, relatively disorderly, so the official launch of the subprocess, the goal is to provide a unified module to implement the system command or script calls

The Subprocess module allows-spawn new processes, connect to their input/output/error pipes, and obtain their retur N Codes. This module intends to replace several older modules and functions:

    • Os.system
    • os.spawn*

The recommended approach to invoking subprocesses are to use the run () function for all use cases it can handle. For cases, the underlying Popen interface can used directly.

The run () function is added in Python 3.5; If you need to retain compatibility with older versions, see the older high-level API section.

Three ways to execute commands

    • Subprocess.run (*popenargs, Input=none, Timeout=none, Check=false, **kwargs) #官方推荐

    • Subprocess.call (*popenargs, Timeout=none, **kwargs) #跟上面实现的内容差不多, another way of writing

    • Subprocess. Popen () #上面各种方法的底层封装

Run () method

Run command with arguments and return a completedprocess instance. The returned instance would have attributes args, ReturnCode, stdout and stderr. By default, stdout and stderr is not captured, and those attributes would be None. Pass stdout=pipe and/or stderr=pipe in order to capture them.

If check is True and the exit code was Non-zero, it raises a calledprocesserror. The Calledprocesserror object'll has the return code in the ReturnCode attribute, and output & stderr attributes if Those streams were captured.

If timeout is given, and the process takes too long, a timeoutexpired exception would be raised.

The other arguments is the same as for the Popen constructor.

Standard notation

In [5]:ImportSubprocessin [6]: Subprocess.run (['DF','- H'],stderr=subprocess. Pipe,stdout=subprocess. pipe,check=True) out[6]: completedprocess (args=['DF','- H'], returncode=0, stdout=b'Filesystem Size used Avail use% mounted on\nudev 5.9G 0 5.9G 0%/DEV\NTMPFS 1.2G 5           0M 1.2G 5%/run\n/dev/sda1 447G 157G 268G 37%/\ntmpfs 5.9G 136M 5.8G 3%/DEV/SHM\NTMPFS  5.0M 4.0K 5.0M 1%/run/lock\ntmpfs 5.9G 0 5.9G 0%/sys/fs/cgroup\n/dev/loop3 84M 84M 0     100%/snap/core/3748\n/dev/loop0 315M 315M 0 100%/snap/pycharm-professional/46\n/dev/loop2 315M 315M  0 100%/snap/pycharm-professional/45\n/dev/loop1 84M 84M 0 100%/snap/core/3604\ncgmfs 100K 0 100K 0%/run/cgmanager/fs\ntmpfs 1.2G 108K 1.2G 1%/run/user/1000\n/dev/loop4 315M 315M 0 100%/  SNAP/PYCHARM-PROFESSIONAL/47\N/DEV/LOOP5 82M 82M 0 100%/snap/core/3887\ntmpfs 1.2G 0 1.2G 0% /run/user/1001\n', stderr=b"')

The command that involves piping | must be written like this

In [7]: Subprocess.run ('df-h|grep disk1'#shell=true means that this command is given directly to the system to execute, No python is required to parse Out[7]: completedprocess (args='df-h|grep disk1', returncode=1)
Call () method
#executes the command, returns the command execution status, 0 or not 0>>> retcode = Subprocess.call (["ls","- L"])#executes the command, returns normally if the command result is 0, or throws an exception>>> Subprocess.check_call (["ls","- L"]) 0#receives a string format command, returns a tuple form, the 1th element is the execution state, and the 2nd is the command result>>> Subprocess.getstatusoutput ('Ls/bin/ls') (0,'/bin/ls')#receives a string format command and returns the result>>> Subprocess.getoutput ('Ls/bin/ls')'/bin/ls'#executes the command and returns the result, noting that the result is returned, not printed, and the following example returns to Res>>> Res=subprocess.check_output (['ls','- L'])>>>Resb'Total 0\ndrwxr-xr-x-Alex Staff 408 2 11:05 oldboycrm\n'
Popen () method

Common parameters:

    • The Args:shell command, which can be a string or sequence type (for example: list, tuple)
    • stdin, stdout, stderr: Indicates the standard input, output, and error handles of the program, respectively
    • PREEXEC_FN: Valid only on UNIX platforms, specifying an executable object (callable object) that will be called before the child process is run
    • Shell: Ibid.
    • CWD: Used to set the current directory of child processes
    • ENV: The environment variable used to specify the child process. If env = None, the environment variables of the child process are inherited from the parent process.

What is the difference between the following 2 statements execution?

A=subprocess.run ('sleep', shell=true,stdout=subprocess. PIPE) a=subprocess. Popen ('sleep', shell=true,stdout=subprocess. PIPE)

The difference is that Popen will return immediately after the command is launched, without waiting for the command to execute the result. What are the benefits of this?

If you call the command or script need to execute 10 minutes, your main program does not need to wait here for 10 minutes, you can continue to go down, do other things, every once in a while, through a method to detect whether the command is completed.

The Popen call returns an object that can be used to get command execution results or state, and the object has the following methods

poll()

Check If child process has terminated. Returns ReturnCode

wait()

Wait for the child process to terminate. Returns ReturnCode attribute.

terminate()Terminates the process started terminate the processes with SIGTERM

kill()Kill the process that was started kill the procedure with SIGKILL

communicate()Interacts with the initiated process, sends data to STDIN, receives output from stdout, and waits for the task to end

>>> a = subprocess. Popen ('python3 guess_age.py', stdout=subprocess. Pipe,stderr=subprocess. Pipe,stdin=subprocess. Pipe,shell=True)>>> a.communicate (b') ( B ') Your guess:try bigger\n', b')

send_signal(signal.xxx)Send System signal

pidGet the process number of the startup process

Python Basics-4.13 subprocess Module

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.