:
import subprocess
import contextlib
@contextlib.contextmanager
def noop():
yield None
logging = False
file_path = '/tmp/out'
with open(file_path, 'wb') if logging else noop() as shell_stdout:
subprocess.call(['ls'], stdout=shell_stdout)
True . logging False, noop() ( with-statement), shell_out None, .
, stdout=None,
... ; childs .
stdout sys.stdout. , sys.stdout , (, sys.stdout = open('/tmp/stdout', 'wb')), , , , sys.stdout. , fileinput sys.stdout. noop() stdout stdout, sys.stdout.
, Padraic Cunningham solution :
with open(file_path, 'wb') if logging else sys.stdout as shell_stdout:
subprocess.call(['ls'], stdout=shell_stdout)