我可以用Python中的一个命令写入终端和给定文件吗?

Nat*_*nus 2 python windows python-2.6 python-idle

我已经看到这个问题在参考Bash时得到了解答,但是找不到Python的一个.抱歉,如果这是重复的事情.

是否可以使用一个命令打印到终端和输出文件?我熟悉使用print >>和sys.stdout = WritableObject,但我想避免为我想要记录的每一行双重打印命令.

我正在使用Python 2.6,以防万一这样的知识是必要的.

更重要的是,我希望这可以使用IDLE的命令行在基于Windows的系统上运行.所以,实质上,我希望python脚本向IDLE的终端和给定的日志文件报告.

编辑:对于任何发现这个并决定选择答案的人,如果你需要帮助理解上下文管理器(就像我做的那样),我推荐Doug Hellman的本周Python模块进行澄清.这个详细介绍了上下文库.有关装饰器的帮助,请参阅Stack Overflow问题的答案.

小智 6

替换sys.stdout.

class PrintAndLog(object):
    def __init__(self, fileOrPath): # choose which makes more sense
        self._file = ...

    def write(s):
        sys.stdout.write(s)
        self._file.write(s)

    def close(self):
        self._file.close()
    # insert wrappers for .flush, .writelines

_old_stdout = sys.stdout
sys.stdout = PrintAndLog(f)
... # print and stuff
sys.stdout = _old_stdout
Run Code Online (Sandbox Code Playgroud)

可以放入上下文管理器(这至少是我第三次在SO上看到类似的东西......):

from contextlib import contextmanager

@contextmanager
def replace_stdout(f):
    old_stdout = sys.stdout
    try:
        sys.stdout = PrintAndLog(f)
        yield
    finally:
        sys.stdout = old_stdout
Run Code Online (Sandbox Code Playgroud)