How to get python script file path that has been compiled in binary .exe?
Question:
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
Answers:
I would suggest using sys.argv
to access command line parameters. The first value in sys.argv
is the name of the program. e.g:
...
filenameOnly = sys.argv[0]
exeFile = filenameOnly + '.exe'
...
Here are some related stackoverflow links for further reading on this subject.
How to input arguments after compiling python program with PyInstaller
I solved the problem with src = sys.executable
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
I would suggest using sys.argv
to access command line parameters. The first value in sys.argv
is the name of the program. e.g:
...
filenameOnly = sys.argv[0]
exeFile = filenameOnly + '.exe'
...
Here are some related stackoverflow links for further reading on this subject.
How to input arguments after compiling python program with PyInstaller
I solved the problem with src = sys.executable