In your case, you can use fileinputmodule :
from fileinput import FileInput
with FileInput(args.infile) as file:
process(file)
args.infile='-', sys.stdin. inplace=True, sys.stdout . . , , stdin.
:
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')
, stdout .
sys.stdin / sys.stdout, ExitStack :
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)
else:
output_file = stack.enter_context(open(args.output, 'w'))
process(files, output_file)