I'm kinda new to python and shell (and programming in general...) My problem is, I was given an environment, which is working fine, and I need to activate this environment in order to start a python script.
Doing this manually in the shell (I'm on windows) works perfectly (ie activating the environment using "activate myenv", and then starting my script using "python myprog.py".
Now, I would like to do all of that just from a python script. I would like to start a script in my shell which activate my environment in that shell and then start myprog.py
I've check on the internet and found "os.system" and "subprocess.run", but both don't work
myprog.py
import subprocess
subprocess.run(['activate','myenv'], shell=True)
print('done')
This is a short script to activate my environment according to what i found on the internet. Must put shell=True otherwise I have an error : FileNotFoundError: [WinError 2] The system cannot find the file specified
Executing myprog.py using the command "python myprog.py" works perfectly, but the environment in my shell isn't activated. But if I write directly in my shell "activate myenv" the environment activates
It's because it only activates env for your subprocess command. The command is created in a child process, not in the main process (where you run your python script).
When this line ends, your child process is terminated:
subprocess.run(['activate','myenv'], shell=True)
There was an old post but it's hacky.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.