如何在 Python 的一个程序中导入/使用库(pytorch)的两个不同版本? [英] How can I import/use two different versions of a library (pytorch) in one program in Python?

查看:205
本文介绍了如何在 Python 的一个程序中导入/使用库(pytorch)的两个不同版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在同一个 python 网络服务器的不同部分使用两个不同版本的 pytorch.不幸的是,我无法在我使用的同一个 conda 环境中安装它们.我试过从路径本身导入其中之一:

I need to use two different versions of pytorch in different parts of the same python webserver. Unfortunately, I can't install them both on the same conda environment that I'm using. I've tried importing one of them from the path itself:

MODULE_PATH = "/home/abc/anaconda3/envs/env/lib/python3.7/site-packages/torch/__init__.py"
MODULE_NAME = "torch"
import importlib
import sys
spec = importlib.util.spec_from_file_location(MODULE_NAME, MODULE_PATH)
module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module
spec.loader.exec_module(module)

这对于导入与活动环境中的版本不同的版本效果很好,但是在尝试导入第二个版本时遇到了错误(我尝试过简单的导入火炬",也与上述相同):

Which works fine for importing a different version than the one in the active environment, but then I run into an error when trying to import the second one (I've tried simply 'import torch' and also the same as above):

File "/home/abc/anaconda3/envs/env2/lib/python3.7/site-packages/torch/__init__.py", line 82, in <module>
    __all__ += [name for name in dir(_C)
NameError: name '_C' is not defined

关于如何使用这两个版本的任何想法?谢谢!

Any ideas on how I can use both versions? Thanks!

推荐答案

原则上,导入两个同名的库是不可能的.当然,情况可能是你可以做一些进口魔法并设法做到这一点.但请记住,pytorch 不是一个简单的 Python 包.

In principle, importing two libraries with the same name is not possible. Sure, it might be the case that you could do some import-sorcery and manage to do it. But keep in mind that pytorch is not a straightforward Python package.

现在,即使你设法解决了这个问题,我觉得你自己的服务需要两个不同的版本似乎非常奇怪.从长远来看,遇到这种情况只会让您头疼.我的建议是重新考虑你是如何做的.

Now, even if you manage to solve this, it seems extremely strange to me that you need for your own service two different versions. Having that situation will just be a headache for you in the long run. My advice would be to reconsider how you're doing it.

在不了解您的情况的情况下,我建议将 Web 服务一分为二.这将允许您拥有两个环境和您需要的两个版本的 pytorch.

Without knowing your situation, I'd recommend splitting the web service into two. This will allow you to have two environments and the two versions of pytorch you need.

这篇关于如何在 Python 的一个程序中导入/使用库(pytorch)的两个不同版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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