为什么``__file__```目录一直转到AppData?

问题描述 投票:0回答:1

我正在开发一个大型项目,并且即将完成,所以我想到安装 pyinstaller,以便我可以将 python 脚本转换为 .exe 文件。

当我运行 .exe 文件时,出现错误“未处理的异常..”,基本上是说我在脚本中放置到文件中的目录之一不存在。目录是:

'C:\\Users\\user\\AppData\\Local\\Temp\\_MEI45202\\Images\\SaveChangesButton.png'

但这不应该是目录。这是一个具有相同问题的替代脚本(它更短):

import os
from PIL import Image

filepathforpythonfile = __file__
filepathforpythonfile = filepathforpythonfile.replace("Understanding OSModule.py", "")
filepathforpythonfile = filepathforpythonfile + "/Images/SaveChangesButton.png"
__file__ = os.path.abspath(filepathforpythonfile)
im = Image.open(__file__)
im.show()

它工作得很好。事实上,如果我在 IDE 中运行

print(__file__)
,图像的文件目录就完美地出来了。

当我使用 pyinstaller 将 top 转换为 .exe 文件时,操作系统而非 IDE 出现错误。该目录位于 \AppData\Local 或我不知道的随机目录。

现在,我必须说我对路径和目录以及操作系统模块的了解非常有限,所以请忍受我的无知。非常感谢。

注意:这里的“Understanding OSModule.py”是.py 文件的名称。图像文件夹与 .py 文件位于同一文件夹中。

python path operating-system pyinstaller filepath
1个回答
0
投票

我不认为你仍然有这个问题,因为你问这个问题已经过去了两年了,但我会回答它,因为我确信仍然有人面临同样的问题。

问题是,当您使用 PyInstaller 创建 .exe 文件并运行它时,它会在 \AppData\Local\Temp... 目录中执行,因此程序认为所需的文件位于该文件夹中。

一个解决方案是这样的:

exe_path = os.path.abspath(sys.argv[0])
exe_dir = os.path.dirname(exe_path)
im = Image.open(exe_dir)
© www.soinside.com 2019 - 2024. All rights reserved.