0

I looked up few documentation and utilizing venv package, i'm tyring to create a virtual environment programatically,then activate it and install libraries to run my script . however , when i try this (sample below) , in my mac, it doesn't work and i get error => bash: source ven/bin/activate: No such file or directory.

import os
import subprocess
import venv

v_name = "ven"

# Create the virtual environment
builder = venv.EnvBuilder(system_site_packages=False, clear=True, symlinks=False, upgrade=False, with_pip=True)
builder.create(v_name )

#activate
virtual_path = os.path.join(v_name , "bin", "activate")
subprocess.call([f"bash", f"source {virtual_path }"])
ozil
  • 599
  • 7
  • 31

1 Answers1

0

To activate a virtual environment programmatically, you can use the activate_this.py script that comes with virtual environments in Python. Here's an updated version of your code:

import os
import subprocess
import venv

v_name = "ven"

# Create the virtual environment
builder = venv.EnvBuilder(system_site_packages=False, clear=True, symlinks=False, upgrade=False, with_pip=True)
builder.create(v_name)

# Activate the virtual environment
activate_path = os.path.join(v_name, "bin", "activate_this.py")
exec(open(activate_path).read(), {'__file__': activate_path})

# Install libraries or run your script within the activated virtual environment
subprocess.call(["pip", "install", "library_name"])  # Example: Install a library

# Run your script or perform other tasks within the activated virtual environment
subprocess.call(["python", "your_script.py"])  # Example: Run a Python script

In this updated code, we use the activate_this.py script to activate the virtual environment. Then, you can install libraries or run your script within the activated virtual environment using subprocess.call.