Execute external commands in python (both receiving/not receiving results)

Confirmed to work with python3, MacOS and Linux.

import os
import subprocess


def exec_os_system(cmd: str):
    '''
Execute commands synchronously
Standard output and standard error output are displayed at any time at the prompt executed.
The return value is the return code of the command
    '''
    # os.Since system waits for the end of the child process with wait, the return code is stored in the upper 8 bits of the return code.
    #Shift to 8bit right to take it
    # see http://d.hatena.ne.jp/perlcodesample/20090415/1240762619
    rt = os.system(cmd) >> 8
    return rt


def exec_subprocess(cmd: str, raise_error=True):
    '''
Execute commands synchronously
The standard output and standard error output are returned together at the end.
    raise_Throw an exception if error is True and return code is non-zero
The return value is a 3-value tuple(Standard output(bytes type),Standard error output(bytes type),Return code(int))
    '''
    child = subprocess.Popen(cmd, shell=True,
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = child.communicate()
    rt = child.returncode
    if rt != 0 and raise_error:
        raise Exception(f"command return code is not 0. got {rt}. stderr = {stderr}")

    return stdout, stderr, rt


if __name__ == "__main__":
    exec_os_system("date")

    stdout, stderr, rt = exec_subprocess("date")
    print(stdout)
    print(stderr)
    print(rt)


Execution result

Fri Dec 18 16:04:49 JST 2020
b'Fri Dec 18 16:04:49 JST 2020\n'
b''
0

Recommended Posts

Execute external commands in python (both receiving/not receiving results)
Execute external command in python
Check for external commands in python
How to execute external shell scripts and commands in python
[Mac] A super-easy way to execute system commands in Python and output the results
External command execution in Python
Create your own Linux commands in Python
How to execute commands in jupyter notebook
[Python] Saving learning results (models) in machine learning
Image sending / receiving memo in Python (Flask)
To execute a Python enumerate function in JavaScript
Load and execute command from yml in python
Create a package containing global commands in Python