In your case, you could use fileinput
module:
from fileinput import FileInput
with FileInput(args.infile) as file:
process(file)
# sys.stdin is still open here
If args.infile='-'
then it uses sys.stdin
. If inplace=True
parameter then it redirects sys.stdout
to the input file. You could pass several filenames. If there are no filenames it uses filenames given at the command-line or stdin.
Or you could leave the file as is:
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--log', default=sys.stdout, type=argparse.FileType('w'))
args = parser.parse_args()
with args.log:
args.log.write('log message')
# sys.stdout may be closed here
It should be fine for most programs where stdout may be used to write the result.
To avoid closing sys.stdin / sys.stdout
, you could use ExitStack
to enable the context managers conditionally:
from contextlib import ExitStack
with ExitStack() as stack:
if not args.files:
files = [sys.stdin]
else:
files = [stack.enter_context(open(name)) for name in args.files]
if not args.output:
output_file = sys.stdout
stack.callback(output_file.flush) # flush instead of closing
else:
output_file = stack.enter_context(open(args.output, 'w'))
process(files, output_file)