Python Forum
finding own python source file to read it - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: finding own python source file to read it (/thread-12500.html)



finding own python source file to read it - Skaperen - Aug-27-2018

i would like to have some code be able to read its own python source file, perhaps by finding it somehow, opening that for reading, then reading it line by line. the difficulty i anticipate is because i want a module to be able to do (reading the modules own source) this and have the implementation be in a module. then what if it is being run from a .pyc or .pyo file (assuming the source exists). if the source is not present, then return something to indicate that or raise an exception.


RE: finding own python source file to read it - perfringo - Aug-27-2018

I don't know whether it's useful information, but there is linecache - random access to text lines module which per documentation: "The linecache module allows one to get any line from a Python source file"


RE: finding own python source file to read it - Gribouillis - Aug-27-2018

Use the __file__ variable.


RE: finding own python source file to read it - Skaperen - Aug-27-2018

it seems to work. i want to test this with a .pyc file but i can't seem to get python3 to make one anywhere. the man page is not helpful. does anyone know how to get it to do that?