获取导入模块的路径 [英] Get path of importing module

查看:100
本文介绍了获取导入模块的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个python文件:main.py和imported.py.我想将imported.py导入到main.py中,但是我想访问文件imported.py中的main.py路径.那就是我要访问导入模块的路径.例如:

I have two python files: main.py and imported.py. I want to import imported.py into main.py but I want access to the path of main.py in the file imported.py. That is I want access to the path of the importing module. For example:

#main.py
import imp
imported = imp.load_source('imported', "/absolute/path/to/imported.py")

#imported.py
pathToImportingModule=os.path.??? 
doSomethingWithPath(pathToImportingModule)

推荐答案

从ekhumoro收到的评论中的解决方案:

Solution received in comments from ekhumoro:

#main.py
import imp
imported = imp.load_source('imported', "/absolute/path/to/imported.py")


#imported.py
pathToImportingModule=os.path.abspath(sys.modules['__main__'].__file__)    
doSomethingWithPath(pathToImportingModule)

这篇关于获取导入模块的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆