将输出打印到日志文件并显示它

问题描述 投票:0回答:2

我正在寻找一种将输出打印到日志文件中的方法,但我也想在我的 pycharm 调试器中看到。

我找到了这个,但它只打印到文件中:

log = open("myprog.log", "a")
sys.stdout = log

>>> print("Hello")
>>> # nothing is printed because it goes to the log file instead.

有什么办法吗?

python python-3.x output
2个回答
1
投票

如果可以的话,避免更换

sys.stdout
,在这里你可以。

log_file = open('myprog.log', 'a')
def log(text):
    print(text)
    log_file.write(str(text) + '\n')

log('hello')

0
投票

以与@PiMarillion答案相同的方式,但更简洁(使用

with open
)并且可用,即使该函数是在另一个文件中定义的:

def log_text(log_file_path, verbose, text):
    """
    Function to print text in console and add it to a log file.

    :param log_file_path: path of the log file
    :param verbose: boolean parameter, when True text is printed to terminal
    :param text: string of the message to print and write
    :return: nothing
    """

    if verbose:
        print(text)

    with open(log_file_path, "a") as lf:
        lf.write(text + "\n")

    return

请注意,

verbose
参数是可选的,拥有这种参数只是很方便。

然后您可以在代码中的任何位置调用此函数。

© www.soinside.com 2019 - 2024. All rights reserved.