Situation: My Python script has a line of code that copies itself to another directory
shutil.copyfile(os.path.abspath(__file__), newPath)
Problem: The script is then compiled into an EXE and ran. The error given is as follows:
FileNotFoundError: No such file or Directory: "C:\Path\To\EXE\script.py"
As you can see, the EXE is looking for the .py
version of itself (i.e. uncompiled version)
Question: Is there another Python command that can still let the executable find itself and not the .py
version of itself?
Additional information: I was going to try to just replace .py
with .exe
and see if it works -- it would have if not for the program to fail if I change the name of the executable.
C:\ > script.exe
#Works as expected
C:\ > ren script.exe program.exe
C:\ > program.exe
FileNotFoundError: No such file or directory: "C:\script.py"
I was stuck in this problem too. Finally I found the solution from the official document.
Solution:
Use sys.argv[0]
or sys.executable
to access the real path of the executed file.
Explanation:
This is because your executable is a bundle
environment. In this environment, all the __file__
constants are relative paths relative to a virtual directory (actually the directory where the initial entrance file lies in).
As instructed by the document, you can access the absolute by using sys.argv[0]
or sys.executable
, as they are pointing to the actually executed command. So in a bundle
environment, you call script.exe
, and sys.executable
will be script.exe
. While in a running live environment, you call python script.path
, and sys.executable
will be python.exe
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With