Python Basic-subprocess module

Source: Internet
Author: User
Tags stdin

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,

>>> OS. system(' Uname-a ') Darwin Alexs-macbook-pro.local 15.6.0 Darwin Kernel Version 15.6.04 21:43:07 PDT 2017:xnu-3248.70.< Span class= "token number" >3~1 /release_x86_64 x86_640        

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

subprocess.run([‘df‘,‘-h‘],stderr=subprocess.PIPE,stdout=subprocess.PIPE,check=True)

The command that involves piping | must be written like this

subprocess.run(‘df -h|grep disk1‘,shell=True) #shell=True的意思是这条命令直接交给系统去执行,不需要python负责解析
Call () method
#执行命令,返回命令执行状态 , 0 or 非0>>> retcode = subprocess.call(["ls", "-l"])#执行命令,如果命令结果为0,就正常返回,否则抛异常>>> subprocess.check_call(["ls", "-l"])0#接收字符串格式命令,返回元组形式,第1个元素是执行状态,第2个是命令结果 >>> subprocess.getstatusoutput(‘ls /bin/ls‘)(0, ‘/bin/ls‘)#接收字符串格式命令,并返回结果>>> subprocess.getoutput(‘ls /bin/ls‘)‘/bin/ls‘#执行命令,并返回结果,注意是返回结果,不是打印,下例结果返回给res>>> res=subprocess.check_output([‘ls‘,‘-l‘])>>> resb‘total 0\ndrwxr-xr-x 12 alex staff 408 Nov 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 10‘,shell=True,stdout=subprocess.PIPE)a=subprocess.Popen(‘sleep 10‘,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,stderr=subprocess ,stdin=subprocess ,shell=true>>> A.communicate" "  (B ' your guess:try bigger\n ' )     

send_signal(signal.xxx)Send System signal

pidGet the process number of the startup process

Python Basic-subprocess module

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.