使用最少量的代码将结果写入文件

时间:2018-05-16 19:55:39

标签: python

我编写的代码适用于我的原因并在终端中显示结果:

print 'The following results are found:'
# some code iterations here
...
...
print 'User - {0}, Title - {1}'.format(...)

目前,我正在尝试实现一个新的可选参数,以便我可以选择是否要将上述结果写入文本文件。

虽然我可以使用它,但它不是最优雅的方法:

# output_to_path is a boolean argument here.

if output_to_file:
    # file_path, I use `open(file_dir, "w")`
    print >> file_path, 'The following results are found:'
print 'The following results are found:'
# some code iterations here
...
...
if output_to_file:
    print 'User - {0}, Title - {1}'.format(...)
print 'User - {0}, Title - {1}'.format(...)

是否可以只编写上述打印语句一次,无论output_to_file是真还是假?我问,因为我开始有大量的印刷声明。

2 个答案:

答案 0 :(得分:1)

以下是使用context manager进行此操作的方法,类似于我在您的问题下面的评论中提到的question答案中的内容。

扭曲的是,为了能够根据需要选择性地打开和关闭文件的输出,最简单的路线似乎是class(而不是应用contextlib '@contextmanager装饰函数就像在那里完成的那样。)

希望这不是太多代码...

import sys

class OutputManager(object):
    """ Context manager that controls whether sysout goes only to the interpreter's
        current stdout stream or to both it and a given file.
    """
    def __init__(self, filename, mode='wt'):
        self.output_to_file = True
        self.saved_stdout = sys.stdout
        self.file = open(filename, mode)
        sys.stdout = self

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        sys.stdout = self.saved_stdout  # Restore.
        self.file.close()

    def write(self, message):
        self.saved_stdout.write(message)
        if self.output_to_file:
            self.file.write(message)

    def enable(self):
        self.output_to_file = True

    def disable(self):
        self.output_to_file = False


if __name__ == '__main__':
    # Sample usage.
    with OutputManager('cmtest.txt') as output_manager:
        print 'This line goes to both destinations.'
        output_manager.disable()
        print 'This line goes only to the display/console/terminal.'
        output_manager.enable()
        print 'Once again, to both destinations.'

答案 1 :(得分:1)

您可以编写一个能够满足您需求的功能:

def custom_print(message):
    print(message) # always prints to stdout
    if output_to_file:
        print >> file_path, message

然后你这样称呼它:

custom_print('The following results are found:')
...
custom_print('User - {0}, Title - {1}'.format(...))