[英]Executing python script built under different virtual environment/venv?
I apologize if what I'm trying to achieve is not Pythonic - I recently moved to the language.如果我想要实现的不是 Pythonic,我深表歉意——我最近转向了该语言。
I have a project directory structured like so:我有一个结构如下的项目目录:
root
--proj1
----venv
----main.py
--proj2
----venv
----main.py
Both proj1 and proj2 run under their own virtual environments. proj1 和 proj2 都在它们自己的虚拟环境下运行。 I am trying to call proj2/main.py from proj1/main.py, whilst executing proj2/main.py under its own venv.
我试图从 proj1/main.py 调用 proj2/main.py,同时在它自己的 venv 下执行 proj2/main.py。 I have tried:
我努力了:
import subprocess
s2_out = subprocess.check_output([sys.executable, r"..\proj2\__main__.py", "arg"])
This invokes successfully, but I am getting all manner of not found exceptions, etc. I am guessing this is the reason why.这调用成功,但我得到了各种未找到的异常等。我猜这就是原因。
Please let me know if there is a better approach!请让我知道是否有更好的方法!
You can do this:你可以这样做:
import subprocess
subprocess.call(["python_interpreter location (python.exe)", "python file"])
So you could do:所以你可以这样做:
import subprocess
subprocess.call(["../proj2/bin/python.exe", "proj2/main.py"])
For Mac OS and Linux, the python
interpreter path for a venv would be folder/bin/python.exe
, or in your case ../proj2/bin/python.exe
.对于 Mac OS 和 Linux,venv 的
python
解释器路径将是folder/bin/python.exe
,或者在您的情况下../proj2/bin/python.exe
。
For Windows, the python
interpreter path for a venv would be folder/scripts/python.exe
.对于 Windows,venv 的
python
解释器路径为folder/scripts/python.exe
。
You may need to include the full paths.您可能需要包含完整路径。
Another way to do this could be using subprocess.call
, if you need the output:如果您需要 output,另一种方法是使用
subprocess.call
:
import subprocess
output = subprocess.call("%s %s" %("../proj2/bin/python.exe", "proj2/main.py"))
print(output)
Both ways will work just fine:)两种方式都可以正常工作:)
Hey this is not a complete answer but is how I would approach it.嘿,这不是一个完整的答案,而是我将如何处理它。 If you use
pyenv
then this would be the approach:如果您使用
pyenv
那么这将是方法:
pyenv virtualenv 3.8 proj1
and pyenv virtualenv 3.7 proj1
or whatever the python versions are. pyenv virtualenv 3.8 proj1
和pyenv virtualenv 3.7 proj1
或任何 python 版本。pyenv local
in each directory to link the dirs to the venvspyenv local
将目录链接到 venvscd
to each directory and in each one the python env should activate. cd
到每个目录,并在每个目录中激活 python 环境。 Use pip install
to install the libs to each venv.pip install
将库安装到每个 venv。~/.pyenv/versions/proj1/bin/python
~/.pyenv/versions/proj1/bin/python
import os;
os.system("~/.pyenv/versions/proj2/bin/python ../proj2/main.py")
or something like that.或类似的东西。 I have not actually tried this but I am fairly certain it would work for using separate libs.
我实际上并没有尝试过,但我相当肯定它适用于使用单独的库。
Here is pyenv: https://github.com/pyenv/pyenv这是pyenv: https://github.com/pyenv/pyenv
I will try it myself tomorrow when I am not sleepy.明天不困的时候我自己试试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.