查找导入模块的绝对路径

时间:2022-03-03 23:18:51

How can I get the absolute path of an imported module?

如何获取导入模块的绝对路径?

3 个解决方案

#1


25  

As the other answers have said, you can use __file__. However, note that this won't give the full path if the other module is in the same directory as the program. So to be safe, do something like this:

正如其他答案所说,你可以使用__file__。但请注意,如果其他模块与程序位于同一目录中,则不会提供完整路径。所以为了安全起见,做这样的事情:

>>> import os
>>> import math
>>> os.path.abspath(math.__file__)
'/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/math.so'

Here's an example with a module I made called checkIP to illustrate why you need to get the abspath (checkIP.py is in the current directory):

这是一个示例,其中我创建了一个名为checkIP的模块来说明为什么需要获取abspath(checkIP.py在当前目录中):

>>> import os
>>> import checkIP
>>> os.path.abspath(checkIP.__file__)
'/Users/Matthew/Programs/checkIP.py'
>>> checkIP.__file__
'checkIP.py'

#2


2  

If it is a module within your PYTHONPATH directory tree (and reachable by placing a __init__.py in its directory and parent directories), then call its path attribute.

如果它是PYTHONPATH目录树中的模块(并且可以通过在其目录和父目录中放置__init__.py来访问),则调用其path属性。

>>>import sample_module
>>>sample_module.__path__
['/absolute/path/to/sample/module']

#3


1  

You can try:

你可以试试:

import os
print os.__file__

to see where the module is located.

查看模块的位置。

#1


25  

As the other answers have said, you can use __file__. However, note that this won't give the full path if the other module is in the same directory as the program. So to be safe, do something like this:

正如其他答案所说,你可以使用__file__。但请注意,如果其他模块与程序位于同一目录中,则不会提供完整路径。所以为了安全起见,做这样的事情:

>>> import os
>>> import math
>>> os.path.abspath(math.__file__)
'/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/math.so'

Here's an example with a module I made called checkIP to illustrate why you need to get the abspath (checkIP.py is in the current directory):

这是一个示例,其中我创建了一个名为checkIP的模块来说明为什么需要获取abspath(checkIP.py在当前目录中):

>>> import os
>>> import checkIP
>>> os.path.abspath(checkIP.__file__)
'/Users/Matthew/Programs/checkIP.py'
>>> checkIP.__file__
'checkIP.py'

#2


2  

If it is a module within your PYTHONPATH directory tree (and reachable by placing a __init__.py in its directory and parent directories), then call its path attribute.

如果它是PYTHONPATH目录树中的模块(并且可以通过在其目录和父目录中放置__init__.py来访问),则调用其path属性。

>>>import sample_module
>>>sample_module.__path__
['/absolute/path/to/sample/module']

#3


1  

You can try:

你可以试试:

import os
print os.__file__

to see where the module is located.

查看模块的位置。