我有一个简单的 Tkinter 桌面应用程序,我最近使用
.exe
制作了它的 pyinstaller
文件。但是,当我想复制文件时它不起作用,因为我总是得到错误的绝对路径。做同样的事情但运行 Python 脚本,而不是 .exe
文件工作正常。当我使用相对路径时,它在 .exe
和 python 文件中都可以正常工作。我该如何解决这个问题?
代码:
def load_map(RL_PATH, map_title):
PATH = pathlib.Path(__file__).parent.absolute()
shutil.copyfile(r'{}\Map Files\{}'.format(PATH, map_title),
r'{}/Labs_Underpass_P.upk'.format(RL_PATH))
我从
.exe
文件中得到的错误信息:
Exception in Tkinter callback
Traceback (most recent call last):
File "tkinter\__init__.py", line 1883, in __call__
File "gui.py", line 154, in <lambda>
def popular_maps_table(self, map_list):
File "gui.py", line 134, in load_map_try
try:
File "load_map.py", line 13, in load_map
shutil.copyfile(r'{}\Map Files\{}'.format(PATH, map_title),
File "shutil.py", line 261, in copyfile
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Martin\\AppData\\Local\\Temp\\_MEI132082\\Map Files\\DribblingChallenge2.udk'
好像
C:\\Users\\Martin\\AppData\\Local\\Temp\\_MEI132082
是.exe
文件的绝对路径。
所以我想通了。 exe文件的绝对路径需要sys.executable
代码:
if getattr(sys, 'frozen', False):
path = os.path.dirname(sys.executable)
elif __file__:
path = os.path.dirname(__file__)
shutil.copyfile(r'{}\Map Files\{}'.format(path, map_title),
r'{}/Labs_Underpass_P.upk'.format(RL_PATH))
原答案:Determining application path in a Python EXE generated by pyInstaller