查找模块的目录

发布于 2024-08-24 09:24:00 字数 174 浏览 4 评论 0原文

如何找到模块导入的目录,因为它需要加载同一目录中的数据文件。

编辑:

结合几个答案:

module_path = os.path.dirname(imp.find_module(self.__module__)[1])

得到了我想要的

How can I find what directory a module has been imported from, as it needs to load a data file which is in the same directory.

edit:

combining several answers:

module_path = os.path.dirname(imp.find_module(self.__module__)[1])

got me what i wanted

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

寻找一个思念的角度 2024-08-31 09:24:00

如果您想通过将 module_name 指定为字符串即不实际导入模块来进入模块目录,则使用

def get_dir(module_name):
    import os,imp
    (file, pathname, description) = imp.find_module(module_name)
    return os.path.dirname(pathname)

print get_dir('os')

输出:

C:\Python26\lib


foo.py

def foo():
    print 'foo'

bar.py

import foo
import os
print os.path.dirname(foo.__file__)
foo.foo()

输出:

C:\Documents and Settings\xxx\My Documents
foo

If you want to modules directory by specifying module_name as string i.e. without actually importing the module then use

def get_dir(module_name):
    import os,imp
    (file, pathname, description) = imp.find_module(module_name)
    return os.path.dirname(pathname)

print get_dir('os')

output:

C:\Python26\lib


foo.py

def foo():
    print 'foo'

bar.py

import foo
import os
print os.path.dirname(foo.__file__)
foo.foo()

output:

C:\Documents and Settings\xxx\My Documents
foo
2024-08-31 09:24:00

这可行:

yourmodule.__file__

如果你想找到导入对象的模块:

myobject.__module__

This would work:

yourmodule.__file__

and if you want to find the module an object was imported from:

myobject.__module__
白芷 2024-08-31 09:24:00

模块文件的路径位于module.__file__中。您可以将其与 os.path.dirname 一起使用来获取目录。

The path to the module's file is in module.__file__. You can use that with os.path.dirname to get the directory.

谜兔 2024-08-31 09:24:00

以 re 模块为例:

>>> import re
>>> path = re.__file__
>>> print path
C:\python26\lib\re.pyc
>>> import os.path
>>> print os.path.dirname(os.path.abspath(path))
C:\python26\lib

请注意,如果该模块位于当前工作目录(“CWD”)中,您将仅获得一个相对路径,例如 foo.py。我养成了立即获取绝对路径的习惯,以防 CWD 在使用模块路径之前发生更改。

Using the re module as an example:

>>> import re
>>> path = re.__file__
>>> print path
C:\python26\lib\re.pyc
>>> import os.path
>>> print os.path.dirname(os.path.abspath(path))
C:\python26\lib

Note that if the module is in your current working directory ("CWD"), you will get just a relative path e.g. foo.py. I make it a habit of getting the absolute path immediately just in case the CWD gets changed before the module path gets used.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文