I'm trying to use traceback.print_stack() to print the stack leading up to the error without including the line which actually prints the stack. e.g.:
import os
import pathlib
import sys
import traceback
def main():
path = pathlib.Path('/foo')
content_bytes = b''
my_func(path, content_bytes)
def my_func(path, content_bytes):
for (dirpath, dirnames, filenames) in os.walk(path, onerror=on_error(path)):
for filename in filenames:
file: bytes = open(dirpath + "/" + filename, "rb").read()
content_bytes += file
def on_error(path):
traceback.print_stack(sys._getframe(1))
print("path is not a dir path supplied: {}".format(path))
main()
Assuming I have no dir named /foo
this prints:
path is not a dir path supplied: /foo
File "/{projectDir}/examples/test.py", line 22, in <module>
main()
File "/{projectDir}/examples/test.py", line 10, in main
my_func(path, content_bytes)
File "/{projectDir}/examples/test.py", line 13, in my_func
for (dirpath, dirnames, filenames) in os.walk(path, onerror=on_error(path)):
As I want, but I'm bothered by the fact that I'm calling a protected sys method _getframe
in order to do so. Pycharm also doesn't seem happy with me for doing this. Is there a more appropriate way to getting the current/previous frame in the stack that is used as the first arg of traceback.print_stack
?
I see a lot of previous SO answers based on sys.exc_info()
but this appears to be a tuple filled with None objects in this case.