Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can install Django project requirement.txt with python script

I am creating a single script for setup and running whole Django project.

venv_parent_dir = os.path.abspath(os.path.join(os.getcwd(),os.pardir))
venv_dir = os.path.abspath(os.path.join(venv_parent_dir, 'fvenv'))
subprocess.run(args=['virtualenv', '-p', 'python3', venv_dir])
os.popen('/bin/bash --rcfile %s'%(venv_dir+'/bin/activate'))

With the above code I created a virtual environment then activate this. Now I want to install the requirements.txt file in the activated virtual environment

subprocess.run(args=['pip3', 'install', '-r', 'requirements.txt'])

I tried with subprocess, but it's not installing in the virtual environment, it is installing in the operating system Python.

like image 481
Hitesh Roy Avatar asked Nov 19 '25 09:11

Hitesh Roy


1 Answers

A the moment, the os.popen command does not affect the environment that subprocess.run runs in. That means that your subprocess.run call is using the system pip3 instead of the pip from the virtualenv. You can use the pip from the virtualenv by using the full path:

import os
pip = os.path.join(venv_dir, 'bin', 'pip')
subprocess.run(args=[pip, 'install', '-r', 'requirements.txt'])

By using /path/to/venv/bin/pip, you don't have to activate the virtual environment first.

like image 153
Alasdair Avatar answered Nov 21 '25 00:11

Alasdair



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!