Search code examples
pythonpython-os

How to get python script file path that has been compiled in binary .exe?


I have python script myscript.py that I compiled with pyinstaller with the following command: pyinstaller -F myscript.py . Now I get a file called myscript.exe . In my script, there are line that I wrote to get the path of this file using the following code:

this_file = os.path.realpath(__file__)
src = this_file
filenameOnly, file_extension = os.path.splitext(src)
exeFile = filenameOnly+'.exe'
print ('exe file to check', exeFile)
if os.path.exists(exeFile):
    src = exeFile
print ('Binary file', src)

But this works well only if the .exe file is having the same name as the initial .py file. If I rename the binary file, my script will not detect that change


Solution

  • I solved the problem with src = sys.executable