简体   繁体   English

在 Python 中使用虚拟环境导入模块

[英]Import module with virtual environment in Python

so here is my question:所以这是我的问题:

Script A imports Script B , Script A uses Virtual Environment A and Script B uses Virtual Environment B . Script A导入Script BScript A使用Virtual Environment AScript B使用Virtual Environment B

import sys

interpreterPath = "[...]/.env/bin/python"


if sys.executable != interpreterPath:
    import subprocess

    print("Creating subprocess...")
    subprocess.Popen([interpreterPath,__file__])
    print("Subprocess has exited.")
else:
    ############################
    ###   SUBPROCESS START   ###

    import module

    # TODO

The importing of the module after "SUBPROCESS START" works fine, it just does not return functions I define where the "TODO" is located at.在“SUBPROCESS START”之后导入模块工作正常,它只是不返回我定义的“TODO”所在位置的函数。

How would I archive this?我将如何存档? Thanks for helping.感谢您的帮助。

In principle, it is a very common scenario that you describe: most non-trivial projects depend on other libraries that have dependencies themselves.原则上,这是您描述的一个非常常见的场景:大多数不平凡的项目依赖于其他本身具有依赖关系的库。 However, you need to differentiate here properly between dependencies (ie other libraries) and virtual environments, which are a means to install those dependencies in an isolated manner.但是,您需要在此处正确区分依赖项(即其他库)和虚拟环境,这是一种以隔离方式安装这些依赖项的方法。

So coming back to your question, your project A should depend on project B and you run both in project A's virtual environment.所以回到您的问题,您的项目 A 应该依赖于项目 B,并且您在项目 A 的虚拟环境中运行两者。

How that is implemented in detail, depends a bit on how your projects are set up.具体如何实现,在一定程度上取决于您的项目是如何设置的。

Think of virtual environments like "working boxes" for projects ie when you're within one virtual environment, you're isolated from any others you may have.将虚拟环境想象为项目的“工作箱”,即当您处于一个虚拟环境中时,您将与您可能拥有的任何其他环境隔离。 Virtual environments allow you to manage dependencies and ensure you have no version conflicts etc. between other projects on the same machine.虚拟环境允许您管理依赖关系并确保您在同一台机器上的其他项目之间没有版本冲突等。

It's important to understand the difference between what I'm referring to as a project vs an individual script .理解我所说的项目与单个脚本之间的区别很重要。

In this scenario, where you have 2 scripts, but one is importing modules from another one, you really have one project which contains 2 scripts.在这种情况下,您有 2 个脚本,但其中一个正在从另一个导入模块,您确实有一个包含 2 个脚本的项目 The fact that the two scripts have different requirements doesn't matter, since you need to run both , ie need one virtual environment.这两个脚本有不同的要求这一事实并不重要,因为您需要同时运行这两个脚本,即需要一个虚拟环境。

By defining virtual environments for the scripts separately, you're not actually using the virtual environment for the script which is referenced from the main one.通过分别为脚本定义虚拟环境,您实际上并没有为从主脚本引用的脚本使用虚拟环境。

Links you might find helpful:您可能会发现有用的链接:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM