'How to get source code of current module when the code is compiled using pyinstaller

In my GUI application written in Python with Tkinter, I'm trying to add a new tab to the Notebook widget named "Source Code" which would get the source code using inspect module and show it with IDLE's syntax highlighting in a Text widget.

from tkinter import Frame, Text
from idlelib.percolator import Percolator
from idlelib.colorizer import ColorDelegator

class sourceFrame(Frame):
    def __init__(self, master, **kwargs):
        super().__init__(master=master, **kwargs)
                        
        self.sourceText = Text(self, state="disabled", wrap="none", bg="white", relief="flat", takefocus=0, highlightthickness=0)
        Percolator(self.sourceText).insertfilter(ColorDelegator())
                        
        self.sourceText.replace(inspect.getsource(__import__("sys").modules[__name__]))
        self.sourceText.pack(expand=1, fill="both")

The above code works perfectly fine when I run the code normally. However, when I pack the code to an *.exe file using pyinstaller and run the *.exe, I get an error:

Traceback (most recent call last):
  File "main.pyw", line 102, in wrapper
  File "main.pyw", line 2129, in __init__
  File "main.pyw", line 2120, in __init__
  File "main.pyw", line 2112, in __init__
  File "inspect.py", line 1147, in getsource
  File "inspect.py", line 1129, in getsourcelines
  File "inspect.py", line 958, in findsource
OSError: could not get source code

Is there any way to get the source code of current module even if the code was compiled into an *.exe file?



Sources

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

Source: Stack Overflow

Solution Source