Python is going to call a subprocess, the user either requested that subprocesses stdout is to go to a file (or back-holed to os.devnull), or the subprocesses output is to be passed though "in real time".
My current best guess as how to do this would seemingly work:
- Let
file_path
be valid input foropen()
- Let
logging
be a Boolean indicator, true indicating usefile_path
for logging or false to passthough to stdout.
with open(file_path, 'wb') if logging else None as shell_stdout:
subprocess.call(['ls'], stdout=shell_stdout)
In tinkering/testing this appears to be the right value, which I have assumed work well with subprocess.call. However, and unsurprisingly I get the following exception:
AttributeError: __exit__
So None
is not a context, it has no __exit__
;
Goals
- Not open a file at all if the user does not want logging.
- Use contexts (as provided by the stdlib), (Preference; I can't imagine doing the file open/close operations manually being any cleaner.)
- Not need a try/catch (Preference to avoid further nesting)
- Only have a single call to
subprocesses.call
(Non duplicated line)
So, how could this behavior be achieved? Or what would you suggest doing instead/alternatively?