Home > Back-end >  print traceback to file when there is no exception
print traceback to file when there is no exception

Time:11-12

What specific Python 3 syntax must be changed below in order to successfully print a trackback form a successfully running function into a file that is located at aValidFileNameAndPath?

We need this to work in normal running functions where there is NO exception.

The Python 3 code we are using is:

import traceback
traceback.print_stack(file=aValidFileNameAndPath)

The error thrown by the above code is:

File "C:\path\to\script\in\our\app\ourScriptName.py", line 69, in ourFunctionName
  traceback.print_stack(file=aValidFileNameAndPath)
File "C:\Program Files\Python39\lib\traceback.py", line 190, in print_stack
  print_list(extract_stack(f, limit=limit), file=file)
File "C:\Program Files\Python39\lib\traceback.py", line 25, in print_list
  print(item, file=file, end="")
AttributeError: 'str' object has no attribute 'write'

The other postings we have found on stack overflow have to do with printing exceptions. We do NOT want to print an exception. Instead, we just want to print out the chain of functions that called a specific function during normal functioning of the app when there is no exception to be thrown.

CodePudding user response:

You are getting this error because where you are using the file path the code wants a file object.


To make a file object, use open, e.g. myfile = open(aValidFileNameAndPath)

You will also want to set the file to writing mode, e.g. open(path, 'w')

Then you can pass myfile as a paremeter, e.g. traceback.print_stack(file=myfile)

Then make sure to close the file with close


Here is a full example:

import traceback

myfile = open(aValidFileNameAndPath, 'w')  # note that this will delete anything that alredy exists in the file
traceback.print_stack(file=myfile)
myfile.close()
  • Related