subprocess01.py

#! /usr/bin/python3
# ==================================================================
# Use the subprocess module
#
# From: www.youtube.com/watch?v=2Fp1N6dofOY
#       Calling External Commands Using the Subprocess Module
# ==================================================================
#
# Notes:
#
# a. capture_output was introduced in Python 3.7
#    p1 = subprocess.run(['ls','-al'],capture_output=True,text=True)
#
# b. test=True introduced in Python 3.7
#
# c. decode() converts returned byte string b'.....' to text
#
# ==================================================================

import subprocess
from subprocess import PIPE

p1 = subprocess.run(['ls','-al'], stdout=PIPE, stderr=PIPE)

print(p1.stdout.decode())
##print(p1.stdout)


# ---- returned code

p2 = subprocess.run(['ls','-al','xyz'], stdout=PIPE, stderr=PIPE)

print('Returned code is {}'.format(p2.returncode))
print(p2.stderr.decode())
##print(p2.stderr)


# ---- redirect output to a file

with open('output.txt', 'w') as f:
    p3 = subprocess.run(['ls'], stdout=f)
    if p3.returncode == 0:
        print('Output written to file')
    else:
        print('Write to file failed')
        print(p3.stderr.decode())