Python3+
在进行脚本打包后转移后运行,发现相关资源文件无法找到了,经分析问题出在脚本打包后由于不再是由Python解释脚本的形式运行,__file__变量会失去作用。此时具有类似效用的是sys.executable。
hasattr() 函数可用于判断对象是否包含对应的属性。
hasattr(object, name)
object -- 对象。
name -- 字符串,属性名。
def hasattr(*args, **kwargs): # real signature unknown
"""
Return whether the object has an attribute with the given name.
This is done by calling getattr(obj, name) and catching AttributeError.
"""
pass
举例
class hasattr_test:
a = 1
b = 'str'
c = True
test = hasattr_test()
print(hasattr(test, 'a'))
print(hasattr(test, 'b'))
print(hasattr(test, 'c'))
print(hasattr(test, 'd'))
print(hasattr(test, 'e'))
结果
True
True
True
False
False
用下方用法可以解决转移打包的可执行文件无法找到资源文件路径问题,不过有一点需要注意,资源文件和可执行文件的相对路径不要变。
import sys
import os
def exe_path():
if hasattr(sys, 'frozen'):
# dirname是获取指定路径的上一层文件路径
return os.path.dirname(sys.executable)
# __file__返回的内容是脚本的绝对路径
return os.path.dirname(__file__)
if __name__=='__main__':
print(exe_path())
结果
C:/Users/admin/Desktop/resource/
脚本实际位置
C:/Users/admin/Desktop/new/resource/test.py