用 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()