1

I would like to print on a .txt or .log file everything that would be printed on the terminal especially the errors.

In this example I put an error when clicking the button and would like it to be captured and printed on the file.

In this case the error is known to occur when the button is clicked. But I would like any errors that may occur while using the program to be captured and printed to the file

import tkinter as tk

def on_click():
    # this error is made specifically to explain what I would like to achieve
    print(int("string"))

# Create the window
win = tk.Tk()
win.geometry("500x300")
win.title("window")

# Create the button
tk.Button(win, text="Button", command=on_click).pack()

if __name__ == "__main__":
    win.mainloop()

this in the photo is an example of the error I would like to capture

enter image description here

1
  • First apply Exception Handling then write the exception to a log file. You can also use logging for this. Commented Jul 20, 2021 at 17:05

2 Answers 2

1

You can redirect errors in file using file descriptor 2 while running the script.

python script.py 2> error.txt
Sign up to request clarification or add additional context in comments.

Comments

0

For understanding try like this:

import logging

#option 1
logging.basicConfig(filename='log2.txt',filemode='a',format='%(asctime)s - %(message)s', level=logging.ERROR)

#option 2
def log_error(message):
    with open("log.txt", "a+") as myfile:
        myfile.write(f'ERROR : {message} \n')

try:
    1/0
except Exception as e:
    log_error(e)
    logging.error("Exception occurred", exc_info=True)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.