How to import two versions of the same python module at the same time?

☆樱花仙子☆ 提交于 2019-12-09 13:09:32

问题


Suppose I have two versions of a python package, say "lib". One is in folder ~/version1/lib and the other is in ~/version2/lib. I'm trying to load both packages in one session by doing this:

sys.path.insert(0, '~/version1')
import lib as a

sys.path.insert(0, '~/version2')
import lib as b

But it doesn't work, because of cache, b will be the same as a.

Is there anyway to do it? Maybe use hook in sys.meta_path? I didn't figure it out.

Or is there anyway to delete cache of imported modules?


回答1:


  • You can consider using python virtual environment.
  • Activate the required environment and run your code there.



回答2:


You have to import it from one level higher:

import version1.my_lib as a
import version2.my_lib as b

Also make sure that in all the folder there is a __init__.py.



来源:https://stackoverflow.com/questions/29160625/how-to-import-two-versions-of-the-same-python-module-at-the-same-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!