Python中 sys._MEIPASS 是什麼

 

用 pyinstaller 打包生成的 exe 文件,在運行時動態生成依賴文件,sys._MEIPASS 就是這些依賴文件所在文件夾的路徑

通常  C:\Windows\Temp\_MEIxxxx 或 C:\Users\用戶名\AppData\Local\Temp\_MEIxxxx

 僅在 exe 運行時有效,IDE運行時報錯:

AttributeError: module 'sys' has no attribute '_MEIPASS'

sys._MEIPASS 的值在 sys.path 中也可訪問到

 

關於本處詳細參考 https://pyinstaller.readthedocs.io/en/v3.3.1/operating-mode.html

 

_MEIxxxx 文件夾內容舉例:

 

兼顧 exe 運行和 IDE 運行的代碼示例:

# !/usr/bin/python3
# coding: utf-8
import os
import re
import sys
import traceback

this = os.path.abspath(os.path.dirname(__file__))
module = os.path.split(this)[0]
sys.path.append(module)


def match(path):
    basename = os.path.basename(path)
    return re.match("^_MEI\d+$", basename) and True or False


def get():
    try:
        return sys._MEIPASS
    except AttributeError:
        traceback.print_exc()

    for index, path in enumerate(sys.path):
        if match(path):
            return path
    return None


if __name__ == '__main__':
    try:
        path = get()
        print(path)

        if path is not None:
            os.remove(path)
    except PermissionError:
        traceback.print_exc()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章