2012-02-02 192 views

回答

2

foo.py

进口酒吧


bar.py

import traceback 
try: 
    filename,line_number,function_name,text = traceback.extract_stack()[-2] 
    print(filename,line_number,function_name,text) 
except IndexError: 
    pass 

运行foo.py收益率类似

('/home/unutbu/pybin/foo.py', 4, '<module>', 'import bar') 
3

这听起来像你解决了你自己的问题:使用inspect模块。我会遍历堆栈,直到找到当前函数不是__import__的框架。但我敢打赌,如果你告诉人们你为什么要这样做,他们会告诉你不要。

3

即使你得到它的工作,这可能比你想象的有用,因为随后的导入只复制现有的引用,而不是再次执行模块。

+0

这应该可能是一个评论,但是重要的信息。 – 2012-02-02 03:52:28

+1

@Karl:尽管它可以被看作是一个评论,但它在回答“否”的问题上做得很好。 – 2012-02-02 04:10:22

+0

想知道“不建议这样做”背后的原因。我想要做的是提供一个函数** deprecatedModule(new_module)**用于不推荐的模块。 – Drake 2012-02-02 16:17:41

1
import inspect 
result = filter(lambda v:inspect.ismodule(v), globals().values()) 
#result is a collection of all imported modules in the file, the name of any of which can be easily got by .__name__ 
#replace globals() with inspect.getmembers(wanted_module) if you want the result outside the wanted module