Easy Tutorial
❮ C Void Intro Basic Knowledge Summary Of Spring ❯

Python3 subprocess

Category Programming Technology

The subprocess module allows us to start a new process and connect to their input/output/error pipes, thereby obtaining return values.

Using the subprocess module

The subprocess module primarily recommends using its run method, and more advanced usage can directly use the Popen interface.

Syntax format for the run method:

subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None)

The run method returns a CompletedProcess instance, similar to directly using Popen, and the implementation is the same, actually calling Popen, with the constructor being roughly the same as Popen, for example:

Example

# Execute the command ls -l /dev/null
>>> subprocess.run(["ls", "-l", "/dev/null"])
crw-rw-rw-  1 root  wheel    3,   2  5  4 13:34 /dev/null
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0)

returncode: The status of the child process after execution. Usually, a return status of 0 indicates that it has finished running. If the value is negative "-N", it indicates that the child process was terminated.

Simple example:

Example

import subprocess
def runcmd(command):
    ret = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8", timeout=1)
    if ret.returncode == 0:
        print("success:", ret)
    else:
        print("error:", ret)

runcmd(["dir", "/b"])  # Sequence parameters
runcmd("exit 1")  # String parameter

Output result:

success: CompletedProcess(args=['dir', '/b'], returncode=0, stdout='test.py\n', stderr='')
error: CompletedProcess(args='exit 1', returncode=1, stdout='', stderr='')

Popen() Method

Popen is the core of subprocess, with the creation and management of child processes handled by it.

Constructor:

class subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, 
preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False, 
startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(),
*, encoding=None, errors=None)

Common parameters:

Create a child process and execute a simple command:

Example

>>> import subprocess
>>> p = subprocess.Popen('ls -l', shell=True)
>>> total 164
-rw-r--r--  1 root root   133 Jul  4 16:25 admin-openrc.sh
-rw-r--r--  1 root root   268 Jul 10 15:55 admin-openrc-v3.sh
...
>>> p.returncode
>>> p.wait()
0
>>> p.returncode

Here, you can also create a child process using p = subprocess.Popen(['ls', '-cl']).

Popen Object Methods

Example

import time
import subprocess

def cmd(command):
    subp = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8")
    subp.wait(2)
    if subp.poll() == 0:
        print(subp.communicate()[1])
    else:
        print("Failed")

cmd("java -version")
cmd("exit 1")

Output result:

java version "1.8.0_31"
Java(TM) SE Runtime Environment (build 1.8.0_31-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.31-b07, mixed mode)

Failed

>

Reference articles:

https://blog.csdn.net/weixin_42547344/article/details/80894760

https://blog.csdn.net/maosijunzi/article/details/80138458

** Share My Notes

Cancel

-

-

-

❮ C Void Intro Basic Knowledge Summary Of Spring ❯