【问题标题】:Absolute path of .exe file not working properly in python.exe 文件的绝对路径在 python 中无法正常工作
【发布时间】:2021-06-18 10:40:42
【问题描述】:

我有一个简单的 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 文件的绝对路径。

【问题讨论】:

标签: python pyinstaller exe absolute-path


【解决方案1】:

所以我想通了。 对于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

【讨论】:

    猜你喜欢
    • 2016-03-20
    • 2023-03-26
    • 2021-02-20
    • 2017-06-29
    • 1970-01-01
    • 2015-07-20
    • 2014-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多