繁体   English   中英

重定向 function output 到文本文件

[英]Redirecting function output to text file

我正在尝试将reporterror function 的打印语句重定向到文件中,但是 output 的打印语句没有重定向到文本文件中我可以知道我在这里缺少什么请注意我在这里创建了一个实时场景,我无法将报告错误 function 修改为它在框架中,修改将需要大量测试

import os

def reporterror():
    print ("file not found")
    errors = ["error", "error1", "error3"]
    for er in errors:
        print (er)
    return 1
    
def info():
    print (os.getcwd())
    with open("info.txt", "w") as finfo:
        print(reporterror(), file=finfo)
   
info()

Output in.txt文件:

1个

预计 output:

错误
错误1
错误2

有人已经分享了有关重定向 stdout 的最佳答案的链接,但您还没有找到该答案中可能有帮助的部分。

from contextlib import redirect_stdout

with open('log.txt', 'w') as f:
    with redirect_stdout(f):
        my_function() #Call your function here any prints will go to the file
        print("This text") #This will be output to the file too

这会将打印的 output 暂时重定向到 log.txt 文件。

您希望reporterror()中的打印语句也写入文件。 然而,这种情况并非如此。 这里唯一发生的事情是reporterror()返回1并打印errors中的每个值。 reporterror()中的打印语句不仅仅从info()中的打印语句继承文件。 下面,我返回一个字符串,其中包含errors中的所有值,后跟一个换行符。 info()中的 print 语句现在将打印reporterror()的 output。

import os

def reporterror():
    errors = ["error", "error1", "error3"] 
    return "\n".join(errors)

def info():
    print (os.getcwd())
    with open("info.txt", "w") as finfo:
        print(reporterror(), file=finfo)

info()

如果要捕获所有output,不管打印语句是否指定output文件,可以通过终端将脚本output重定向到.txt文件:

python script.py > info.txt

值得注意的是,除非您有正当理由使用print()写入文件,否则最好只使用:

file.write(contents)

如果您希望将所有打印语句(AKA 标准 output stdout )output 重定向到特定文件,只需使用此代码段

import sys
sys.stdout = open('<<<PATH_TO_YOUR_FILE>>>', 'w')
print('test')

这将做到这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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