Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start and run a virtualenv in python script? [duplicate]

I'm trying to create a virtual environment, start it, and then have every command after that be executed in the virtual environment.

    1. os.system("curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py")
    2. os.system("python3 get-pip.py")
    3. os.system("mkdir Apps")
    4. os.system("pip3 install virtualenv")
    5. os.system("virtualenv virt")
    6. os.system("source virt/bin/activate")
    7. os.system("pip3 install flask")

This is the code I have right now and I am trying to create the virtual environment on line (5) and then trying to activate it on line (6) and then do the 7th line (install flask) on the virtual environment.

I also have tried os.system('. virt/bin/activate') but every-time I run the python file it goes through and it does everything except start the virtual environment.

I am running this on the terminal on Mac.

like image 496
Nathan Belete Avatar asked Mar 16 '26 14:03

Nathan Belete


1 Answers

Most likely the virtual environment is only active for the duration of the os.system() call. In many cases there is no need to activate the virtual environment, just find its bin directory and run the binaries found in it.

Something of the sort:

  • os.system('/path/to/venv/bin/python -m pip install flask')
  • os.system('/path/to/venv/bin/pip install flask')

For a different approach:

#!/usr/bin/env python3

import pathlib
import subprocess
import venv

class _EnvBuilder(venv.EnvBuilder):

    def __init__(self, *args, **kwargs):
        self.context = None
        super().__init__(*args, **kwargs)

    def post_setup(self, context):
        self.context = context

def _venv_create(venv_path):
    venv_builder = _EnvBuilder(with_pip=True)
    venv_builder.create(venv_path)
    return venv_builder.context

def _run_python_in_venv(venv_context, command):
    command = [venv_context.env_exe] + command
    print(command)
    return subprocess.check_call(command)

def _run_bin_in_venv(venv_context, command):
    command[0] = str(pathlib.Path(venv_context.bin_path).joinpath(command[0]))
    print(command)
    return subprocess.check_call(command)

def _main():
    venv_path = pathlib.Path.cwd().joinpath('virt')
    venv_context = _venv_create(venv_path)
    _run_python_in_venv(venv_context, ['-m', 'pip', 'install', '-U', 'pip'])
    _run_bin_in_venv(venv_context, ['pip', 'install', 'attrs'])

if __name__ == '__main__':
    _main()
like image 186
sinoroc Avatar answered Mar 18 '26 02:03

sinoroc



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!