Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

print traceback to file when there is no exception

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading