Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python subprocess Module

Python subprocess Module

subprocess is a module in the Python standard library used to create and manage child processes.

subprocess lets you execute external commands in a Python program and interact with them.

Pass subprocess With the module, you can execute system commands, call other programs, and get their output or error information.

Why use the subprocess module?

In Python, sometimes we need to run system commands or call other programs to complete specific tasks. For example, you may need to run a shell command, start an external application, or interact with a command-line tool.subprocess The module provides a safe and flexible way to handle these needs.

Compared with the earlier os.system() or os.popen() Compared tosubprocess module, it offers more powerful features and better control. It lets you manage a child process's input, output and error streams more precisely, and handle more complex scenarios.


Core features of the subprocess module

1. Execute external commands

subprocess.run() Is subprocess One of the most commonly used functions in the module. It executes an external command and waits for it to complete. Here is a simple example:

Example

import

subprocess

Execute a simple shell command

result

=

subprocess

.

run

(

[

'ls'

,

'-l'

]

,

capture_output

=

True

,

text

=

True

)

Print the command's output

print

(

result.

stdout

)

In this example,subprocess.run() Executed the ls -l command and captured the output into result.stdout it.

2. Handle input and output

subprocess The module lets you control a child process's input, output and error streams. You can pass data to the child process's standard input, or read from its standard output and standard error. Here is an example:

Example

import

subprocess

Execute a command and pass input to the child process

result

=

subprocess

.

run

(

[

'grep'

,

'python'

]

,

input

=

'hello\npython\nworld'

,

capture_output

=

True

,

text

=

True

)

Print the command's output

print

(

result.

stdout

)

In this example,subprocess.run() Executed the grep python command and pass the string 'hello\npython\nworld' as input to the child process.

3. Handle errors

subprocess The module also lets you handle child process errors. If a child process returns a non-zero exit status code,subprocess.run() raises a CalledProcessError exception. You can check result.returncode to get the child process's exit status code.

Example

import

subprocess

try

:

    result

=

subprocess

.

run

(

[

'ls'

,

'nonexistent_file'

]

,

capture_output

=

True

,

text

=

True

,

check

=

True

)

except

subprocess

.

CalledProcessError

as

e:

   

print

(

f

"Command failed with return code {e.returncode}"

)

   

print

(

f

"Error output: {e.stderr}"

)

In this example,subprocess.run() Executed the ls nonexistent_file command; because the file does not exist, the command fails and raises CalledProcessError exception.


Advanced usage of the subprocess module

1. Use the Popen class

subprocess.Popen The class provides a lower-level interface that gives you more flexible control over child processes. You can use Popen to start a child process and run it in the background, or interact with it.

Example

import

subprocess

Start a child process

process

=

subprocess

.

Popen

(

[

'ping'

,

'google.com'

]

,

stdout

=

subprocess

.

PIPE

,

text

=

True

)

Read the child process's output

while

True

:

    output

=

process.

stdout

.

readline

(

)

   

if

output

==

''

and

process.

poll

(

)

is

not

None

:

       

break

   

if

output:

       

print

(

output.

strip

(

)

)

Get the child process's exit status code

return_code

=

process.

poll

(

)

print

(

f

"Process finished with return code {return_code}"

)

In this example,subprocess.Popen Started a ping google.com command and ran it in the background. The program reads the child process's output in a loop and gets its exit status code after it ends.

2. Use pipes

subprocess The module lets you connect several commands with pipes. You can feed the output of one command into the input of another.

Example

import

subprocess

Connect two commands with a pipe

p1

=

subprocess

.

Popen

(

[

'ls'

,

'-l'

]

,

stdout

=

subprocess

.

PIPE

)

p2

=

subprocess

.

Popen

(

[

'grep'

,

'py'

]

,

stdin

=

p1.

stdout

,

stdout

=

subprocess

.

PIPE

,

text

=

True

)

Get the final output

output

=

p2.

communicate

(

)

[

0

]

print

(

output

)

In this example,ls -l The output of the command is passed to the grep py command, and the final output contains py files or directories.


Common methods, classes and parameters of the subprocess module

The following describes the common methods, classes and parameters of Python's subprocess module, with descriptions and examples:

Core methods of the subprocess module

Method Description Example
subprocess.run() Execute a command and wait for completion (recommended) subprocess.run(["ls", "-l"], capture_output=True, text=True)
subprocess.Popen() Create a child process (low-level control) proc = subprocess.Popen(["ping", "google.com"], stdout=subprocess.PIPE)
subprocess.call() Execute a command and return the exit code (legacy) exit_code = subprocess.call(["python", "--version"])
subprocess.check_call() Execute a command and raise an exception on failure subprocess.check_call(["git", "commit"])
subprocess.check_output() Execute a command and return its output (legacy) output = subprocess.check_output(["date"], text=True)

subprocess.CompletedProcess object attributes (the object returned by run())

property Description
args The command's argument list
returncode The process exit status code (0 means success)
stdout Standard output content (ifcapture_output)
stderr Standard error content (ifcapture_output)

Common methods / attributes of the subprocess.Popen class

Method/attribute Description Example
poll() Check whether the process has terminated (returnsNonemeans still running) if proc.poll() is None: print("Running")
wait() Block until the process ends proc.wait()
communicate() Interactive input / output stdout, stderr = proc.communicate(input="data")
terminate() Send a termination signal (SIGTERM) proc.terminate()
kill() Force-kill the process (SIGKILL) proc.kill()
stdin The process's standard input stream proc.stdin.write("input")
stdout The process's standard output stream print(proc.stdout.read())
stderr The process's standard error stream errors = proc.stderr.read()

Common parameter descriptions (applies to run() and Popen())

Parameters Description Example value
args Command (list or string) ["ls", "-l"] or "ls -l"
stdin Standard input configuration subprocess.PIPE(pipe),None(inherit)
stdout Standard output configuration subprocess.PIPE、open('log.txt', 'w')
stderr Standard error configuration subprocess.STDOUT(merge into stdout)
shell Whether to execute through the Shell True(supports string commands)
cwd Working directory path "/tmp"
env Custom environment variables {"PATH": "/usr/bin"}
timeout Timeout in seconds 30
text Whether input / output is a string (not bytes) True

Example

Execute a command and capture its output:

Example

result

=

subprocess

.

run

(

[

"echo"

,

"Hello"

]

,

capture_output

=

True

,

text

=

True

)

print

(

result.

stdout

)

 

Output: "Hello\n"

Execute a complex command through the Shell:


subprocess.run("grep 'error' log.txt | wc -l", shell=True, check=True)

Get the output stream in real time:

Example

proc

=

subprocess

.

Popen

(

[

"tail"

,

"-f"

,

"log.txt"

]

,

stdout

=

subprocess

.

PIPE

)

while

True

:

    line

=

proc.

stdout

.

readline

(

)

   

if

not

line:

break

   

print

(

line.

decode

(

)

.

strip

(

)

)

Timeout control:

Example

try

:

   

subprocess

.

run

(

[

"sleep"

,

"10"

]

,

timeout

=

5

)

except

subprocess

.

TimeoutExpired

:

   

print

(

"Command timed out!"

)