I would like to write a python script that does 3 things :
In my project I use the normal virtualenviroment package . and I have to do it on a Debian machine.
I tried to mimic the bash command with os.system()
but didn't make it with the code below.
import os
os.system('python3 -m venv test6_env')
os.system('source test6_env/bin/activate')
os.system('pip install -r requirements.txt --user')
Problem the virtualenv will not activated and the requirements not installed.
Is there a easy trick to script in python this 3 stepy nicely ?
To use the virtual environment you created to run Python scripts, simply invoke Python from the command line in the context where you activated it. For instance, to run a script, just run python myscript.py .
Activating the virtual environment will change your shell's prompt to show what virtual environment you're using, and modify the environment so that running python will get you that particular version and installation of Python.
The problem is that os.system('source test6_env/bin/activate')
activates the virtual environment only for the subshell spawned by this particular os.system()
call, and not any subsequent ones. Instead, run all shell commands with a single call, e.g.
os.system('python3 -m venv test6_env && . test6_env/bin/activate && pip install -r requirements.txt')
Alternatively, put your commands in a shell script and execute that with os.system()
or, better yet, using a function from the subprocess
module, e.g.
import subprocess
subprocess.run('/path/to/script.sh', check=True)
I had to make one approach right now, so i will leave it here. You must have virtualenv installed. Hope helps someone :)
def setup_env():
import virtualenv
PROJECT_NAME = 'new_project'
virtualenvs_folder = os.path.expanduser("~/.virtualenvs")
venv_dir = os.path.join(virtualenvs_folder, PROJECT_NAME)
virtualenv.create_environment(venv_dir)
command = ". {}/{}/bin/activate && pip install -r requirements.txt".format(virtualenvs_folder, PROJECT_NAME)
os.system(command)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With