[英]How to abstract stdin/stdout and files?
I'm trying to write a Python script which lets the user to switch between stdin/stdout and files for input/output.我正在尝试编写一个 Python 脚本,它允许用户在标准输入/标准输出和输入/输出文件之间切换。 But I'm not sure if my implementation is correct:
但我不确定我的实现是否正确:
#!/usr/bin/python3
import fileinput
import sys
from contextlib import contextmanager
from contextlib import redirect_stdout
def foo(file):
return ''.join([line for line in file])
@contextmanager
def run(input_file, output_file):
stdin = '-' if input_file is None else input_file
stdout = sys.stdout if output_file is None else open(output_file, 'w')
with fileinput.input(stdin) as stdin, stdout:
with redirect_stdout(stdout):
print(foo(stdin))
I think you would need to do this way.我认为你需要这样做。 You don't need to make
run()
itself a @contextmanager
—all it needs to do is use one (or more, and both fileinput.input
and redirect_stdout
are ones already).你不需要让
run()
本身成为一个 @ @contextmanager
它需要做的就是使用一个(或多个, fileinput.input
和redirect_stdout
已经是一个)。 I'm not sure why you're using fileinput.input
since there appears to only be one input file involved.我不确定您为什么使用
fileinput.input
因为似乎只涉及一个输入文件。
from contextlib import redirect_stdout
import fileinput
import sys
def foo(file):
return ''.join([line for line in file])
def run(input_file, output_file):
stdin = '-' if input_file is None else input_file
stdout = sys.stdout if output_file is None else open(output_file, 'w')
with fileinput.input(stdin) as stdin, redirect_stdout(stdout):
print(foo(stdin))
run('input.txt', 'output.txt')
run('input.txt', None)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.