Bundling data files with PyInstaller (--onefile)

前端 未结 13 1584
清歌不尽
清歌不尽 2020-11-21 13:28

I\'m trying to build a one-file EXE with PyInstaller which is to include an image and an icon. I cannot for the life of me get it to work with --onefile.

<
13条回答
  •  粉色の甜心
    2020-11-21 14:04

    All of the other answers use the current working directory in the case where the application is not PyInstalled (i.e. sys._MEIPASS is not set). That is wrong, as it prevents you from running your application from a directory other than the one where your script is.

    A better solution:

    import sys
    import os
    
    def resource_path(relative_path):
        """ Get absolute path to resource, works for dev and for PyInstaller """
        base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
        return os.path.join(base_path, relative_path)
    

提交回复
热议问题