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

前端 未结 4 2012
暖寄归人
暖寄归人 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: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, '', 'import bar')
    

提交回复
热议问题