How to use the subprocess module for subprocess management in Python 2.x

PHPz
Release: 2023-07-30 10:07:58
Original
1138 people have browsed it

How to use the subprocess module for subprocess management in Python 2.x

Overview:
In Python development, sometimes we need to call other external commands or programs in the program. The subprocess module is a standard library provided by Python, which can easily create and communicate with subprocesses. This article will introduce how to use the subprocess module for subprocess management and illustrate it with code examples.

  1. Create a subprocess:
    The most commonly used function in the subprocess module is subprocess.Popen(), which can start a new process and return a Popen object. The basic syntax for using the Popen() function to create a subprocess is as follows:
import subprocess

subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, 
                 close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, 
                 creationflags=0)
Copy after login

Parameter description:

  • args: string or sequence type command Line parameters
  • bufsize: Parameters that control the size of the input and output buffers. 0 represents no buffering, 1 represents line buffering, and other positive numbers represent the buffer size.
  • executable: The path to the executable file, default Use the search path in the system PATH environment variable
  • stdin: The standard input stream of the child process, the default is PIPE, that is, input through the stdin attribute of the Popen object
  • stdout: The standard output of the child process Stream, the default is PIPE, which is output through the stdout attribute of the Popen object
  • stderr: The standard error stream of the child process, the default is PIPE, which is output through the stderr attribute of the Popen object
  • preexec_fn : An executable object that will be called before the child process is started
  • close_fds: Whether to close file descriptors that are no longer needed, the default is False
  • shell: Whether to perform command parsing through the shell, Default is False
  • cwd: Working directory, default is None
  • env: Environment variable, default is None, that is, use the environment variable of the parent process
  • universal_newlines: Control input and output Whether to convert to text mode, the default is False
  • startupinfo: The startup information of the child process, the default is None
  • creationflags: The creation flag of the child process, the default is 0

Sample code 1: Start a subprocess and execute the command, and then obtain the output of the subprocess.

import subprocess

cmd = "ls -l"
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
output, _ = p.communicate()
print(output)
Copy after login
  1. Input and output of the subprocess:
    When creating a subprocess, we can specify the subprocess through the stdin, stdout, and stderr parameters of the Popen() function. input Output. If these parameters are not specified, a new pipe will be created by default and read and written through the properties of the Popen object.

Sample code 2: Start a child process and perform input and output through pipes.

import subprocess

cmd = "grep -E 'a|b|c'"
p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
input_data = "abcdefg
hijklmnop
qrstuvwxyz
"
output, _ = p.communicate(input_data)
print(output)
Copy after login

Sample code 3: Start a subprocess and redirect output to a file.

import subprocess

cmd = "grep -E 'a|b|c' input.txt > output.txt"
subprocess.Popen(cmd, shell=True)
Copy after login
  1. Waiting for the end of the child process:
    The execution of the child process is asynchronous. By default, the Popen() function will return a Popen object immediately instead of Wait for the child process to complete execution. If we need to wait for the child process to complete execution before proceeding to the next step, we can use the wait() method of the Popen() object.

Sample code 4: Start a child process and wait for its execution to complete.

import subprocess

cmd = "ls -l"
p = subprocess.Popen(cmd, shell=True)
p.wait()
print("子进程执行完毕")
Copy after login
  1. Capture the exit status code of the child process:
    Each child process will have an exit status code, representing its execution result. You can use the returncode attribute of the Popen() object to obtain the exit status code of the child process. If it is 0, it means the execution is successful.

Sample code 5: Get the exit status code of the child process.

import subprocess

cmd = "ls -l"
p = subprocess.Popen(cmd, shell=True)
p.wait()
if p.returncode == 0:
    print("子进程执行成功")
else:
    print("子进程执行失败")
Copy after login

Summary:
Through the subprocess module, we can easily create subprocesses and manage processes in Python programs. Specific operation methods include creating a child process, controlling the input and output of the child process, waiting for the child process to end, and capturing the exit status code of the child process. Mastering this knowledge can better utilize Python for sub-process management and improve the flexibility and scalability of the program.

The above is the relevant content about using the subprocess module for subprocess management in Python 2.x. Hope this helps.

The above is the detailed content of How to use the subprocess module for subprocess management in Python 2.x. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template