请注意,python 命名空间非常强大。希望这个小例子能对您有所帮助。
基本理论是,将不同版本的相同库添加到Python的类路径中,并使它们具有不同的名称,这样就不会发生覆盖。
import os, sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'libs'))
上面的代码将在项目基目录下的“libs”目录下插入第三方库。
假设我需要 2.4.1 和 2.6.1 版本的 pycrypto,使用pip install pycrypto==2.6.1 -t ./libs
and ip install pycrypto==2.4.1 -t ./libs
将两个版本安装到项目下的子目录中。安装后修改它们的名称,否则它将覆盖现有的。
Modify their names to Crypto241 and Crypto261 seprately.
假设我有两个模块(ModuleWIthCrypto241
, ModuleWithCrypto261
)这将分别导入 pycrypto 2.4.1 和 2.6.1。
ModuleWithCrypto261 代码:
def getCryproVersion(baseDir):
import os, sys
sys.path.insert(0, os.path.join(baseDir, 'libs'))
import Crypto261
return Crypto261.__version__
ModuleWIthCrypto241 代码:
def getCryproVersion(baseDir):
import os, sys
sys.path.insert(0, os.path.join(baseDir, 'libs'))
import Crypto241
return Crypto241.__version__
几乎一样,只是导入不同版本的pycrypto。
然后我们有另一个脚本尝试获取两个不同版本的 pycrypto。modulewithdiffversion.py
它看起来像什么:
import os, sys
from com.x import ModuleWIthCrypto241
from com.x import ModuleWithCrypto261
if __name__ == '__main__':
baseDir = os.path.dirname(os.path.abspath(__file__))
print ModuleWIthCrypto241.getCryproVersion(baseDir)
print ModuleWithCrypto261.getCryproVersion(baseDir)
执行main方法,它会打印出pycrypto的两个版本:
2.4.1
2.6.1
希望对你有帮助!