#!/usr/bin/env python3 import argparse import sys import subprocess from contextlib import redirect_stderr, redirect_stdout def test(script): with open('out.log', 'w') as out, open('err.log', 'w') as err: with redirect_stdout(out), redirect_stderr(err): cmd = [script, '-o'] # These 2 should be equivalents since stdout=None and # stderr=None will make the child process to inherit the # fds from the parent (?) ret = subprocess.run(cmd) # Doesn't use the redirected stdout/stderr ret = subprocess.run(cmd, stdout=None, stderr=None) # Doesn't use the redirected stdout/stderr ret = subprocess.run(cmd, stdout=sys.stdout, stderr=sys.stderr) def nested(script): with open('nestedout.log', 'w') as out, open('nestederr.log', 'w') as err: cmd = [script] ret = subprocess.run(cmd, stdout=out, stderr=err) def output(): print("This is stdout") print("This is stderr", file=sys.stderr) def entrypoint(): parser = argparse.ArgumentParser() parser.add_argument( '-o', '--output', action='store_true', help=('Whether to print to stdout and stderr or run the actual test')) parser.add_argument( '-n', '--nested', action='store_true', help=('Whether to run this script nested')) args = parser.parse_args() if args.output: output() elif args.nested: nested(sys.argv[0]) else: test(sys.argv[0]) if __name__ == '__main__': entrypoint()