目录
问题描述
pyinstaller 打包py文件成exe文件,执行打包后的程序,经常会出现程序使用的配置文件无法关联,或者,在打包后的路径下运行正常,但是将打包后的程序放到其它路径下就有问题。
这些现象都很有可能是因为程序使用的文件路径发生改变产生的,因此在打包时候我们需要根据执行路径进行路径“冻结”。
Python项目打包后,找不到配置文件路径
1.冻结路径
如何‘冻结’路径呢?
创建一个frozen.py的文件
import os
import sys
def app_path():
if hasattr(sys, 'frozen'):
return os.path.dirname(sys.executable) #使用pyinstaller打包后的exe目录
return os.path.dirname(__file__) #没打包前的py目录
hasattr()内置函数:
英文文档:
hasattr(object, name)
The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an AttributeError or not.)
- 说明: 函数功能用来检测对象object中是否含有名为name的属性,如果有则返回True,如果没有返回False
其中的app_path()函数返回一个程序的执行路径,为了方便我们将此文件放在项目文件的根目录,通过这种方式建立了相对路径的关系。
源代码中使用路径时,以app_path()的返回值作为基准路径,其它路径都是其相对路径。
2.使用方法
例如:
在需要使用路径的py文件中,import frozen
import frozen
# Windows
if os.name == 'nt':
config_path = frozen.app_path() + r'\config.conf' #配置文件路径
# linux
else: