我有两个脚本,我们将它们称为 master.py
和 subject.py
。 master.py
应该在 Python3 中运行,而 subject.py
在 Python2 中运行,因此我为它们创建了两个单独的 Conda 环境,我们将其称为 env -master
和 env-subject
。但是,master.py
应该作为子进程运行 subject.py
。像这样的东西:
subprocess.run('conda run -n env-subject python2 /path/to/subject.py')
真的有可能让这样的事情发挥作用吗?因为,据我了解,任何时候只能有一个 conda 环境处于事件状态。我想知道是否有解决方法可以基本上使用 master.py
运行多批 subject.py
,同时分析已完成的任何执行的输出文件,并且从不分析一次运行超过 N 个 subject.py
。
最佳答案
对我来说效果很好。这是一个例子:
脚本
so-py23-mix.py
import sys
import subprocess
print("This is the main process")
print(sys.version)
subprocess.run(['conda', 'run', '-n', 'so-py2', 'python', 'so-py2-sub.py'])
so-py2-sub.py
import sys
print "This is the subprocess"
print sys.version
正在运行
shell 命令
mamba create -yn so-py2 python=2
mamba create -yn so-py3 python=3
mamba activate so-py3
python so-py23-mix.py
输出
This is the main process
3.10.5 | packaged by conda-forge | (main, Jun 14 2022, 07:09:13) [Clang 13.0.1 ]
This is the subprocess
2.7.15 | packaged by conda-forge | (default, Mar 5 2020, 14:58:04)
[GCC Clang 9.0.1 ]
运行 2
也可以在不激活的情况下获得完全相同的行为,而是通过 conda run
启动:
外壳
mamba create -yn so-py2 python=2
mamba create -yn so-py3 python=3
conda run -n so-py3 --live-stream python so-py23-mix.py
结果
This is the main process
3.10.5 | packaged by conda-forge | (main, Jun 14 2022, 07:09:13) [Clang 13.0.1 ]
This is the subprocess
2.7.15 | packaged by conda-forge | (default, Mar 5 2020, 14:58:04)
[GCC Clang 9.0.1 ]
请注意,我的基础环境是 Python v3.8。
关于python - 从另一个 Conda 环境中的脚本内运行 Conda 环境中的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72663449/