Where is module being imported from?

前端 未结 8 1366
余生分开走
余生分开走 2020-12-07 19:57

Assuming I have two Python modules and path_b is in the import path:

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

#file: path_a/app.py
impo         


        
8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 20:33

    There may be an easier way to do this, but this works:

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

    Note that the path will be printed relative to the current working directory if it's a parent directory of the script location.

提交回复
热议问题