Pyinstaller EXE's __file__ refers to a .py file

↘锁芯ラ 提交于 2019-12-11 00:31:50

问题


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"

回答1:


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.




回答2:


Try the following:

from os.path import abspath, splitext
fromfile_without_ext, ext = splitext(abspath(__file__))
shutil.copyfile(fromfile_without_ext + '.exe', newPath)

(Did not test it, but should work...)



来源:https://stackoverflow.com/questions/50959340/pyinstaller-exes-file-refers-to-a-py-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!