[英]Absolute path of .exe file not working properly in python
我有简单的 tkinter 桌面应用程序,我最近使用 pyinstaller 制作了一个.exe 文件。 但是,当我想复制文件时它不起作用,因为我总是得到错误的绝对路径。 做同样的事情,但运行 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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.