Python's subprocess module

Source: Internet
Author: User

I. INTRODUCTION

Subprocess was first introduced in version 2.4. Used to generate child processes, and to connect their input/output/errors through pipelines, and to get their return values.

# subprocess is used to replace multiple old modules and functions os.systemos.spawn*os.popen*popen2.*commands.*

When we run Python, we are all creating and running a process where a process in Linux can fork a subprocess and have the child process exec another program. In Python, we fork a child process through the subprocess package in the standard library and run an external program. The subprocess package defines a number of functions that create child processes, each of which creates sub-processes in different ways, and we can choose one to use as needed. In addition, Subprocess provides some tools for managing standard streams and pipelines (pipe) to use text communication between processes.

Two. Use

1. Call

Execute command, return status code, Shell = True allow shell command when string form

Subprocess.check_call (["LS", "-l"]) Subprocess.check_call ("Exit 1", shell=true)

2. Check_call

Executes the command, returns 0 if the execution status code is 0, or throws an exception

Subprocess.check_call (["LS", "-l"]) Subprocess.check_call ("Exit 1", shell=true)

3. Check_output

Executes the command, if the status code is 0, returns the execution result, or throws an exception

Subprocess.check_output (["echo", "Hello world!"]) Subprocess.check_output ("Exit 1", shell=true)

4. subprocess. Popen (...)

Used to perform complex system commands

Parameters:

    • args: Can be a string or sequence type (for example: list, tuple). By default, the program to be executed should be the first field of the sequence, and if it is a single string, its resolution depends on the platform. In Unix, if Args is a string, the string is interpreted as the name or path of the executed program, however, this can only be used in programs that do not require parameters.
    • Bufsieze: Specifies buffering. 0 for unbuffered, 1 for buffering, any other integer value for buffer size, negative for using system default buffering, usually for full buffering. The default value is 0 without buffering.
    • stdin, stdout, stderr: Represents a program's standard input, output, error handle
    • PREEXEC_FN: Only available on UNIX platforms, specifying an executable object that will be called before it runs in a child process
    • Close_fds: Under the Windows platform, if Close_fds is set to true, the newly created child process will not inherit the input, output, and error pipes of the parent process. Therefore, you cannot set Close_fds to true while redirecting the standard input, output, and error of the child process.
    • Shell: The default value is False, which declares whether the shell is used to execute the program, and if shell=true, it considers args as a string, not a sequence. In Unix systems, and shell=true, the shell uses/bin/sh by default.
    • CWD: Used to set the current directory of the child process. When it is not none, the current path of the subroutine is replaced with the value of CWD before it executes. This path is not added to the executable's search path, so CWD cannot be a relative path.
    • 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. When it is not none, it is a mapping of the environment variables of the new process. It can be used in place of the current process environment.
    • Universal_newlines: Unlike line breaks for different systems, file objects stdout and stderr are opened as text files
    • startupinfo and Createionflags only takes effect under Windows. will be passed to the underlying CreateProcess () function, which sets some properties of the child process, such as: the appearance of the main window, the priority of the process, and so on

To execute a common command:

Import Subprocessret1 = subprocess. Popen (["mkdir", "T1"]) Ret2 = subprocess. Popen ("mkdir T2", shell=true)

The commands for terminal input are divided into two types:

    1. Input can be output, such as: ifconfig
    2. Input to an environment that relies on input, such as: Python
Import subprocessobj = subprocess. Popen ("mkdir T3", Shell=true, cwd= '/home/dev ',)
Import subprocessobj = subprocess. Popen (["Python"], stdin=subprocess. PIPE, Stdout=subprocess. PIPE, Stderr=subprocess. PIPE, Universal_newlines=true) obj.stdin.write ("Print (1) \ n") Obj.stdin.write ("Print (2)") obj.stdin.close () Cmd_out = Obj.stdout.read () obj.stdout.close () Cmd_error = Obj.stderr.read () obj.stderr.close () print (cmd_out) print (cmd_error)
Import subprocessobj = subprocess. Popen (["Python"], stdin=subprocess. PIPE, Stdout=subprocess. PIPE, Stderr=subprocess. PIPE, Universal_newlines=true) obj.stdin.write ("Print (1) \ n") Obj.stdin.write ("Print (2)") Out_error_list = Obj.communicate () print (out_error_list)
Import subprocessobj = subprocess. Popen (["Python"], stdin=subprocess. PIPE, Stdout=subprocess. PIPE, Stderr=subprocess. PIPE, universal_newlines=true) out_error_list = Obj.communicate (' Print ("" Hello ") ') print (out_error_list)

Note: More details about subprocess click here

Python's 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.