简体   繁体   English

如何抽象标准输入/标准输出和文件?

[英]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))
  1. Is the code managing resources correctly?代码管理资源是否正确?
  2. How can I properly handle character encoding?如何正确处理字符编码? I'd like to have everything in utf-8.我想拥有 utf-8 格式的所有内容。
  3. Is there any room for improvement in the above code?上面的代码还有改进的余地吗?

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.inputredirect_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM