Python hasattr()笔记(可执行文件路径获取)

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值