This page looks best with JavaScript enabled

Python subprocess

 ·  ☕ 2 min read

The subprocess Module

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import subprocess

process = subprocess.Popen(
    ["executable", "arg1", "arg2", ..., "argn"],  # must be strings or pathlib.Path-like objects (with string representation)
    cwd=work_dir,  # path to executable is always relative to cwd; executable is launched with cwd as working directory 
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE
)
stdout, stderr = process.communicate()
exit_code = process.returncode

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import subprocess
from pathlib import Path

def execute_binary(executable, arguments=[], work_dir='.'):
    if not arguments:
        arguments = []
    if not work_dir:
        work_dir = '.'

    workdir = Path(work_dir).absolute()
        
    process = subprocess.Popen(
        [executable] + list(str(arg) for arg in arguments),
        cwd=work_dir,  # path to executable is always relative to cwd; executable is launched with cwd as working directory 
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    stdout, stderr = process.communicate()
    exit_code = process.returncode
    if exit_code:
        print(f"ERROR {exit_code}: something has gone wrong while executing the binary!")
    else:
        print(f"INFO: all went well while executing the binary!")

    print(f"STDOUT: {stdout.decode('ascii')}")
    print(f"STDERR: {stderr.decode('ascii')}")

    
def execute_binary_2(executable, *args, **kwargs):
   
    work_dir = Path(kwargs.get("work_dir", ".")).absolute()
    print(args)
    print(kwargs)
    print(work_dir)
    process = subprocess.Popen(
        [executable] + list(str(arg) for arg in args),
        cwd=work_dir, 
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    stdout, stderr = process.communicate()
    exit_code = process.returncode
    if exit_code:
        print(f"ERROR {exit_code}: something has gone wrong while executing the binary!")
    else:
        print(f"INFO: all went well while executing the binary!")

    print(f"STDOUT: {stdout.decode('ascii')}")
    print(f"STDERR: {stderr.decode('ascii')}")

Philipp Westphal
WRITTEN BY
Philipp Westphal
Software Developer & Structural Engineer