2012-02-02 190 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