简体   繁体   English

在python代码中激活另一个conda env

[英]activate another conda env inside python code

I need to use both python2.7 and python3.6 for a task. 我需要同时使用python2.7和python3.6进行任务。 I used conda to create two python envs. 我用conda创建了两个python env。 I know how to use a shell script to control the code running and switch between different envs. 我知道如何使用Shell脚本来控制代码运行并在不同的环境之间切换。 Say I need to run python2.7 code first, then I run python 3.6. 假设我需要先运行python2.7代码,然后再运行python 3.6。 My question is could I first run python 2.7 code, and then in the python 2.7 code, I directly activate the python3.6 conda env, and run the python 3.6 code? 我的问题是我可以先运行python 2.7代码,然后在python 2.7代码中直接激活python3.6 conda env,然后运行python 3.6代码吗?

For your task maybe it is enough to change the environment just calling the shell from python using: 对于您的任务,仅使用以下命令从python调用shell即可更改环境:

your python 2.7 code

os.system("Command to change your kernel")  

your python 3.6 code

Maybe you need to add some extra code to take the outputs or new inputs if there are and continue running the code. 也许您需要添加一些额外的代码以获取输出或新的输入(如果有)并继续运行代码。

If that doesn't work maybe is easier to call the python 3.6 function direct from the command: 如果这样不起作用,也许可以直接从命令中更轻松地调用python 3.6函数:

os.system("python3 '/function36.py' ")

Or also using the function subprocess.call from your 2.7 code: 或者,也可以使用2.7代码中的subprocess.call函数:

return_code = subprocess.call("python3 '/function36.py'", shell=True)  

Using Python 3.6 you can also use the subprocess.run() 使用Python 3.6,您还可以使用subprocess.run()

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

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