Is it possible to get “importing module” in “imported module” in Python?

前端 未结 4 2010
暖寄归人
暖寄归人 2021-01-15 11:52

For imported module, is it possible to get the importing module (name)? I\'m wondering if inspect can achieve it or not~

相关标签:
4条回答
  • 2021-01-15 12:11

    It sounds like you solved your own problem: use the inspect module. I'd traverse up the stack until I found a frame where the current function was not __import__. But I bet if you told people why you want to do this, they'd tell you not to.

    0 讨论(0)
  • 2021-01-15 12:16
    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
    
    0 讨论(0)
  • 2021-01-15 12:25

    foo.py:

    import bar


    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
    

    Running foo.py yields something like

    ('/home/unutbu/pybin/foo.py', 4, '<module>', 'import bar')
    
    0 讨论(0)
  • 2021-01-15 12:31

    Even if you got it to work, this is probably less useful than you think since subsequent imports only copy the existing reference instead of executing the module again.

    0 讨论(0)
提交回复
热议问题