模块 __file__ 属性是绝对的还是相对的? [英] Is module __file__ attribute absolute or relative?

查看:41
本文介绍了模块 __file__ 属性是绝对的还是相对的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解 __file__.据我了解, __file__ 返回加载模块的绝对路径.

I'm having trouble understanding __file__. From what I understand, __file__ returns the absolute path from which the module was loaded.

我在生成这个时遇到问题:我有一个 abc.py 和一个语句 print __file__,从 /d/projects/ 运行> python abc.py 返回 abc.py.从 /d/ 运行返回 projects/abc.py.有什么原因吗?

I'm having problem producing this: I have a abc.py with one statement print __file__, running from /d/projects/ python abc.py returns abc.py. running from /d/ returns projects/abc.py. Any reasons why?

推荐答案

来自文档:

__file__ 是加载模块的文件的路径名,如果它是从文件加载的.__file__ 属性对于静态链接到解释器的 C 模块不存在;对于从共享库动态加载的扩展模块,它是共享库文件的路径名.

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

来自@链接的邮件列表主题亲切地对问题发表评论:

From the mailing list thread linked by @kindall in a comment to the question:

我没有试图重现这个特定的例子,但原因是我们不想在每次导入时都调用 getpwd()想要某种进程内变量来缓存当前目录.(getpwd() 相对较慢,有时会失败完全,并且尝试缓存它有一定的错误风险.)

I haven't tried to repro this particular example, but the reason is that we don't want to have to call getpwd() on every import nor do we want to have some kind of in-process variable to cache the current directory. (getpwd() is relatively slow and can sometimes fail outright, and trying to cache it has a certain risk of being wrong.)

相反,我们做的是在 site.py 中遍历元素的代码sys.path 并将它们转换为绝对路径.但是这段代码运行在 '' 之前插入 sys.path 的前面,以便初始sys.path 的值为 ''.

What we do instead, is code in site.py that walks over the elements of sys.path and turns them into absolute paths. However this code runs before '' is inserted in the front of sys.path, so that the initial value of sys.path is ''.

对于其余部分,请考虑 sys.path 不包含 ''.

For the rest of this, consider sys.path not to include ''.

因此,如果您位于包含该模块的 sys.path 部分之外,您将获得一个绝对路径.如果您位于包含该模块的 sys.path 部分,您将获得一个相对路径.

So, if you are outside the part of sys.path that contains the module, you'll get an absolute path. If you are inside the part of sys.path that contains the module, you'll get a relative path.

如果你在当前目录加载一个模块,而当前目录不在sys.path中,你会得到一个绝对路径.

If you load a module in the current directory, and the current directory isn't in sys.path, you'll get an absolute path.

如果你在当前目录加载一个模块,并且当前目录sys.path中,你会得到一个相对路径.

If you load a module in the current directory, and the current directory is in sys.path, you'll get a relative path.

这篇关于模块 __file__ 属性是绝对的还是相对的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆