从哪里导入模块?


72

假设我有两个Python模块,并且path_b在导入路径中:

# file: path_b/my_module.py
print "I was imported from ???"

#file: path_a/app.py
import my_module

是否可以查看从哪里导入模块?如果我启动app.py(因为我需要文件名),我想要一个类似“我是从path_a / app.py导入的”的输出。

编辑: 为了更好的理解;我可以写:

# file: path_b/my_module.py
def foo(file):
    print "I was imported from %s" % file

#file: path_a/app.py
import my_module
my_module.foo(__file__)

因此输出为:

$> python path_app.py
I was imported from path_a/app.py

Answers:


16

可能有一种更简单的方法可以执行此操作,但这可以起作用:

import inspect

print inspect.getframeinfo(inspect.getouterframes(inspect.currentframe())[1][0])[0]

请注意,如果该路径是脚本位置的父目录,则将相对于当前工作目录进行打印。


……更简单的方法是:inspect.stack(0)[1][1]。但是请注意,与在Python 3中相比,您会看到很多importlib相关的信息,因此您可能不得不进行遍历,inspect.stack(0)而不是查找所需的内容。
— ntninja

95

尝试这个:

>>> import my_module
>>> my_module.__file__
'/Users/myUser/.virtualenvs/foobar/lib/python2.7/site-packages/my_module/__init__.pyc'

编辑

在这种情况下,请写入__init__.py模块文件:

print("%s: I was imported from %s" %(__name__, __file__))

4
调用“ app.py”之后,我需要“ my_module”模块中来自“ app.py”的路径。
— svenwltr 2011年

1
这不适用于from module import thing;那么thing.__file__就不会出现。
— Tripleee '16

13

尝试my_module.__file__找出它的来源。如果得到AttributeError,则可能不是Python源(.py)文件。



7

我已经写了一个简单的脚本,所以我有命令pywhich 可以让我找到Python模块的来源。对于某些内置\__file__属性(例如sys),它不起作用,它没有属性。

可以从Linux命令行运行此命令,以查找在当前环境中运行的python脚本将从何处获取模块,例如:

% pywhich os


#! /usr/bin/env python
def pywhich(module_name):
    module = __import__(module_name, globals(), locals(), [], 0)
    return module.__file__

if __name__ == "__main__":
    import sys
    print(pywhich(sys.argv[1]))

请发布示例输出
— not2qubit

使用Python2.7为我工作。我使用python3获得ValueError“ ValueError:级别必须> = 0”
— M. Schlenker

1
根据Python在线手册:在版本3.3中更改:不再支持级别的负值(这还将默认值更改为0)。因此,在对__import__的调用中将-1更改为0
— Adam Anderson,

在2.7中使用0可以使用,所以在给定的示例中已对其进行了更改
— Adam Anderson,

“正是我所需要的。谢谢!
— TheDudeAbides


2

例如setuptools,如果要查看模块的存储位置,请键入shell:

$ python -c "import setuptools; print(setuptools.__file__)"


您将如何获得*.dll与模块相关的路径和名称?(如果在Windows上。)
— not2qubit

ValueError: level must be >= 0在Windows 10上使用Python 3.7运行此错误。
— 艾维格

没有为Seaborn工作;该路径下面的解决方案通过Burkhow一样。
— Mark Andersen

-5

其他的答案是好的,但如果你想从告诉它里面导入的模块,然后做

print "I was imported from %s" % __file__
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.