使用上下文管理器的Python脚本输出到文件? [英] Use a context manager for python script output to a file?

查看:323
本文介绍了使用上下文管理器的Python脚本输出到文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写脚本,在其中有一个选项,可以通过命令行传递,脚本是否应该将结果打印到stdout或预定义的结果文件中。代码大纲如下所示。我现在已经读了一些Python中的上下文管理器,但是我不确定是否以及如何在这个特定的情况下使用上下文管理器。所以我在寻找建议


  1. 在这个问题中使用上下文管理器是否合理


所以,没有上下文管理器的代码是:

  option_file = True#来自于实际代码中的OptionParser 

如果option_file:
out = open(resultsfile,w )
else:
out = sys.stdout

#做一些计算
out.write(脚本的结果)
#更多的计算并调用out.write

如果option_file:
out.close()


和语句使用的东西。它是明确的设计:


  • 执行一些设置,
  • 给你一个对象,
  • / li>


例如,

  • 再次执行一些拆卸操作(即使引发异常) code> open 可以用作上下文管理器。在下面的代码中:

      with open(...)as f:
    #do stuff

    不管什么 stuff 是,文件将始终被关闭。 (通常情况下,除了权力被关闭或进程被杀死之类的愚蠢情况之外)。

    当你处于这种状态时,你应该使用一个上下文管理器情况。它看起来不像我,所以我没有理由为上下文管理器。




    有一个替代方案(不是更好或更差,只是不同)编写你的代码,使用上下文管理器。如果您想要暂时重定向 stdout ,但是确保在完成后恢复它,那么您处于上述情况。这里有一个例子:

    pre $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b sys.stdout = stream
    yield
    sys.stdout = sys .__ stdout__



    <然后,你可以使用open(...)来写代码,例如:

     作为f:
    with redirect_stdout(f ):
    #做东西

    以及任何写到





















    $编辑:你是正确的,没有办法有条件地有一个上下文管理器:要么你在一个或你不是。你可以随时编写你自己的文件,这样做可能什么也不做:

      @ contextlib.contextmanager 
    def maybe_open(path,do_nothing = True):
    if do_nothing:
    f = None
    yield sys.stdout
    else:
    f = open(path)
    yield f

    如果f:
    f.close()

    这几乎肯定是矫枉过正。

    I'm programming a script where I have an option, to be passed on the command line, whether the script should print its results to stdout or to a predefined results file. A code outline for this is shown below. I now have read a little bit about context managers in Python, but am not really sure whether and how to use a context manager in this specific situation. So I am looking for advice

    1. whether it makes sense to use a context manager in this problem
    2. how to go about implementing it.

    So, the code without context manager is:

    option_file = True # would come from OptionParser in real code
    
    if option_file:
        out = open("resultsfile", "w")
    else:
        out = sys.stdout
    
    # do some computations
    out.write("Results of script")
    # more computations and calls to out.write
    
    if option_file:
        out.close()
    

    解决方案

    A context manager is something you can use with a with statement. It is explicitly designed to:

    • perform some setup,
    • give you an object, and
    • perform some teardown again (even if you raise an exception).

    For example, open can be used as a context manager. In the following code

    with open(...) as f:
        # do stuff
    

    it doesn't matter what stuff is, the file will always be closed. (Well, usually. Except in silly cases like the power being turned off or the process being killed.)

    You should use a context manager when you are in this sort of situation. It doesn't look to me like you are, so I see no reason for a context manager.


    There is an alternative (not better or worse, just different) way of writing your code that does use a context manager. If you want to redirect stdout temporarily -- but ensure that you restore it when you're done -- then you are in the situation above. Here's an example:

    @contextlib.contextmanager
    def redirect_stdout(stream):
        import sys
        sys.stdout = stream
        yield
        sys.stdout = sys.__stdout__
    

    You can then write code like

    with open(...) as f:
        with redirect_stdout(f):
            # do stuff
    

    and any writes to stdout in stuff will go to f instead.


    EDIT: You are correct that there is no way conditionally to have a context manager: either you are in one or you aren't. You could always write your own which might do nothing:

    @contextlib.contextmanager
    def maybe_open(path, do_nothing=True):
        if do_nothing:
            f = None
            yield sys.stdout
        else:
            f = open(path)
            yield f
    
        if f:
            f.close()
    

    This is almost certainly overkill.

    这篇关于使用上下文管理器的Python脚本输出到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆