'Got KeyError: '__main__' when I called inspect.stack()[1][3] in python3 virtual environment

I got an error dump when I executed the following code in python

filePath = os.path.join("abc","xyz",inspect.stack()[1][3])

The above line of code is in a function (say f1() ) and gets called by function (say f2() ) So filePath should be

filePath = "abc/xyz/f2"

But when I executed my code in python3 virtual environment, I got the following error dump

    filePath = os.path.join("abc, "xyz", inspect.stack()[1][3])
  File "/usr/lib/python3.9/inspect.py", line 1554, in stack
    return getouterframes(sys._getframe(1), context)
  File "/usr/lib/python3.9/inspect.py", line 1531, in getouterframes
    frameinfo = (frame,) + getframeinfo(frame, context)
  File "/usr/lib/python3.9/inspect.py", line 1505, in getframeinfo
    lines, lnum = findsource(frame)
  File "/usr/lib/python3.9/inspect.py", line 829, in findsource
    module = getmodule(object, file)
  File "/usr/lib/python3.9/inspect.py", line 759, in getmodule
    main = sys.modules['__main__']
KeyError: '__main__'

Please help me resolve this error



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source