【发布时间】:2018-04-01 00:52:36
【问题描述】:
我正在尝试编写一个 Python 脚本,它允许用户在标准输入/标准输出和输入/输出文件之间切换。但我不确定我的实现是否正确:
#!/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))
- 代码管理资源是否正确?
- 如何正确处理字符编码?我希望所有内容都使用 utf-8。
- 上面的代码还有改进的余地吗?
【问题讨论】:
标签: python python-3.x io character-encoding