简体   繁体   中英

Redirecting function output to text file

I am trying to redirect of print statement of reporterror function into file but output of print statement did not redirect into text file May I know what am i missing here Please note I have created one live scenario here and I can not modify report error function as it's in framework and modificaition will require lot of testing

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 file:

1

Expected output:

error
error1
error2

Someone has already shared the link to the top answer on redirecting stdout but you haven't picked up on the part in that answer that might help.

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

This will temporarily redirect the output of print to the log.txt file.

You expect the print statements that are inside reporterror() to also write to the file. However, this is not the case. The only thing that happens here is that reporterror() returns 1 and prints each value in errors . The print statements in reporterror() do not just inherit the file from the print statement in info() . Below, I return a string that contains all of the values in errors followed by a line break. The print statement inside of info() will now print the output of reporterror() .

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()

If you want to capture all output, regardless of whether or not the print statements specify an output file, you can redirect the scripts output into a.txt file through the terminal:

python script.py > info.txt

It should be worth noting that unless you have a valid reason for using print() to write to a file, it is really better off to just use:

file.write(contents)

if you want all the print statements (AKA standard output stdout ) output to be redirect to a specific file just use this snippet

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

this shall do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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