python __file__ is not defined 解决方法

python __file__ is not defined 解决方法

__file__ 是在python module 被导入之后的时候生成的一个变量,所以在 __file__ 不能被使用,但是又想获取当前文件的路径应该怎么做:

方法一:

import inspect, os.path

filename = inspect.getframeinfo(inspect.currentframe()).filename
path     = os.path.dirname(os.path.abspath(filename))

方法二:

import inspect
import os

os.path.abspath(inspect.getsourcefile(lambda:0))

注意:如果需要编译pyd,尽量避免使用inspect,在pyd中获取的路径是错的,这种情况请使用方式三。

方式三:

如果你的模块是在一个package module下(包含__init__的文件夹),用以下方式比较保险,因为__init__.py是不能被编译成pyd的,__file__是存在的,__file__也会存在pyd的模块中,但是要在模块被load的之后,在load的过程中如果调用了,会报错:__file__ is not defined

from . import [ __init__ 中定义的属性 ]

参考链接:https://stackoverflow.com/questions/2632199/how-do-i-get-the-path-of-the-current-executed-file-in-python/18489147#18489147

 

posted @ 2019-05-28 14:55  ibingshan  阅读(9313)  评论(0编辑  收藏  举报