简体   繁体   English

Pyinstaller EXE的__file__指向一个.py文件

[英]Pyinstaller EXE's __file__ refers to a .py file

Situation: My Python script has a line of code that copies itself to another directory 情况:我的Python脚本有一行代码,可将自身复制到另一个目录

shutil.copyfile(os.path.abspath(__file__), newPath)

Problem: The script is then compiled into an EXE and ran. 问题:然后将脚本编译成EXE并运行。 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 (ie uncompiled version) 如您所见,EXE正在寻找其自身的.py版本(即未编译的版本)

Question: Is there another Python command that can still let the executable find itself and not the .py version of itself? 问题:是否还有另一个Python命令仍然可以让可执行文件自行查找,而不是自身的.py版本?

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. 附加信息:我将尝试仅用.exe替换.py并查看其是否有效-如果我更改可执行文件的名称,该程序将失败。

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. 使用sys.argv[0]sys.executable访问已执行文件的真实路径。


Explanation : 说明

This is because your executable is a bundle environment. 这是因为您的可执行文件是bundle环境。 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). 在这种环境中,所有__file__常量都是相对于虚拟目录(实际上是初始入口文件所在的目录)的相对路径。

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. 根据文档的说明,您可以使用sys.argv[0]sys.executable来访问绝对值,因为它们指向实际执行的命令。 So in a bundle environment, you call script.exe , and sys.executable will be script.exe . 因此,在bundle环境中,您调用script.exe ,而sys.executable将是script.exe While in a running live environment, you call python script.path , and sys.executable will be python.exe . 在运行中的实时环境中,您调用python script.path ,而sys.executable将是python.exe

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...) (没有测试,但应该可以工作...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM