Pyinstaller EXE的__file__指向一个.py文件 [英] Pyinstaller EXE's __file__ refers to a .py file

查看:378
本文介绍了Pyinstaller EXE的__file__指向一个.py文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况:我的Python脚本有一行代码,可将自身复制到另一个目录

Situation: My Python script has a line of code that copies itself to another directory

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

问题:然后将脚本编译成EXE并运行.给出的错误如下:

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"

如您所见,EXE正在寻找自身的.py版本(即未编译版本)

As you can see, the EXE is looking for the .py version of itself (i.e. uncompiled version)

问题:是否还有另一个Python命令仍然可以让可执行文件找到自身而不是其自身的.py版本?

Question: Is there another Python command that can still let the executable find itself and not the .py version of itself?

其他信息:我打算尝试用.exe替换.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.

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.

解决方案:

使用sys.argv[0]sys.executable访问已执行文件的真实路径.

Use sys.argv[0] or sys.executable to access the real path of the executed file.

说明:

这是因为您的可执行文件是bundle环境.在这种环境中,所有__file__常量都是相对于虚拟目录(实际上是初始入口文件所在的目录)的相对路径.

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).

根据文档说明,您可以使用sys.argv[0]sys.executable来访问绝对值,因为它们指向实际执行的命令.因此,在bundle环境中,您调用script.exe,而sys.executable将是script.exe.在运行中的实时环境中,您呼叫python script.path,而sys.executable将为python.exe.

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.

这篇关于Pyinstaller EXE的__file__指向一个.py文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆