Python Virtual Environment Setup Scripts: Conda vs Venv Code Examples
Ready-to-use Python scripts for virtual environment setup troubleshooting. Fix conda vs venv issues with these practical code examples and automation tools.
Python Virtual Environment Setup Scripts: Conda vs Venv Code Examples
When your Python virtual environment not working conda vs venv setup needs automation, these ready-to-use scripts provide instant solutions. Copy and customize these code examples to streamline your virtual environment workflow.
Environment Detection Scripts #
Universal Environment Detector #
🐍 Try it yourself
Conda Environment Checker #
🐍 Try it yourself
Automated Setup Scripts #
Venv Environment Creator #
#!/usr/bin/env python3
"""
Automated venv environment setup script
Usage: python setup_venv.py <project_name>
"""
import os
import sys
import subprocess
import argparse
from pathlib import Path
def create_venv_environment(project_name, python_version=None):
"""Create and configure a venv environment"""
# Determine Python executable
if python_version:
python_cmd = f"python{python_version}"
else:
python_cmd = sys.executable
env_path = Path.cwd() / f"{project_name}_env"
print(f"Creating venv environment: {env_path}")
try:
# Create virtual environment
subprocess.run([python_cmd, '-m', 'venv', str(env_path)],
check=True)
# Determine activation script path
if os.name == 'nt': # Windows
activate_script = env_path / 'Scripts' / 'activate.bat'
pip_path = env_path / 'Scripts' / 'pip.exe'
else: # Unix/macOS
activate_script = env_path / 'bin' / 'activate'
pip_path = env_path / 'bin' / 'pip'
print(f"Environment created successfully!")
print(f"Activation script: {activate_script}")
# Upgrade pip
subprocess.run([str(pip_path), 'install', '--upgrade', 'pip'],
check=True)
# Create activation helper script
create_activation_helper(project_name, env_path)
return True
except subprocess.CalledProcessError as e:
print(f"Error creating environment: {e}")
return False
def create_activation_helper(project_name, env_path):
"""Create cross-platform activation helper"""
# Windows batch file
bat_content = f"""@echo off
call "{env_path}\\Scripts\\activate.bat"
echo Virtual environment '{project_name}' activated!
"""
with open(f"activate_{project_name}.bat", 'w') as f:
f.write(bat_content)
# Unix shell script
sh_content = f"""#!/bin/bash
source "{env_path}/bin/activate"
echo "Virtual environment '{project_name}' activated!"
"""
script_path = f"activate_{project_name}.sh"
with open(script_path, 'w') as f:
f.write(sh_content)
# Make shell script executable
os.chmod(script_path, 0o755)
print(f"Activation helpers created:")
print(f" Windows: activate_{project_name}.bat")
print(f" Unix/macOS: activate_{project_name}.sh")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Create venv environment')
parser.add_argument('project_name', help='Name of the project/environment')
parser.add_argument('--python', help='Python version to use')
args = parser.parse_args()
create_venv_environment(args.project_name, args.python)
Conda Environment Creator #
#!/usr/bin/env python3
"""
Automated conda environment setup script
Usage: python setup_conda.py <project_name>
"""
import subprocess
import sys
import argparse
import yaml
def create_conda_environment(project_name, python_version="3.9", packages=None):
"""Create and configure a conda environment"""
packages = packages or ['numpy', 'pandas', 'matplotlib']
print(f"Creating conda environment: {project_name}")
try:
# Create environment with Python version
cmd = ['conda', 'create', '--name', project_name,
f'python={python_version}', '-y']
subprocess.run(cmd, check=True)
# Install packages
if packages:
print(f"Installing packages: {', '.join(packages)}")
install_cmd = ['conda', 'install', '--name', project_name] + packages + ['-y']
subprocess.run(install_cmd, check=True)
# Export environment
export_environment(project_name)
print(f"Conda environment '{project_name}' created successfully!")
print(f"Activate with: conda activate {project_name}")
return True
except subprocess.CalledProcessError as e:
print(f"Error creating conda environment: {e}")
return False
def export_environment(env_name):
"""Export conda environment to YAML file"""
try:
result = subprocess.run(['conda', 'env', 'export', '--name', env_name],
capture_output=True, text=True, check=True)
with open(f"{env_name}_environment.yml", 'w') as f:
f.write(result.stdout)
print(f"Environment exported to {env_name}_environment.yml")
except subprocess.CalledProcessError as e:
print(f"Warning: Could not export environment: {e}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Create conda environment')
parser.add_argument('project_name', help='Name of the project/environment')
parser.add_argument('--python', default='3.9', help='Python version')
parser.add_argument('--packages', nargs='+', help='Packages to install')
args = parser.parse_args()
create_conda_environment(args.project_name, args.python, args.packages)
Troubleshooting Scripts #
Environment Repair Tool #
🐍 Try it yourself
Package Installation Fixer #
🐍 Try it yourself
Cross-Platform Compatibility #
Universal Activation Script #
#!/usr/bin/env python3
"""
Universal virtual environment activation detector and helper
Works with both conda and venv environments
"""
import os
import sys
import platform
from pathlib import Path
def get_activation_command(env_path=None, env_name=None):
"""Generate activation command for current platform"""
system = platform.system().lower()
if env_name: # Conda environment
if system == 'windows':
return f"conda activate {env_name}"
else:
return f"conda activate {env_name}"
elif env_path: # Venv environment
env_path = Path(env_path)
if system == 'windows':
activate_script = env_path / 'Scripts' / 'activate.bat'
return str(activate_script)
else:
activate_script = env_path / 'bin' / 'activate'
return f"source {activate_script}"
return None
def create_universal_activator(project_name):
"""Create universal activation script"""
script_content = f'''#!/usr/bin/env python3
"""
Universal activator for {project_name}
Automatically detects and activates the correct environment
"""
import os
import sys
import subprocess
from pathlib import Path
def activate_environment():
project_dir = Path(__file__).parent
# Look for conda environment
try:
result = subprocess.run(['conda', 'env', 'list'],
capture_output=True, text=True)
if '{project_name}' in result.stdout:
print("Activating conda environment: {project_name}")
if os.name == 'nt':
os.system(f"conda activate {project_name}")
else:
print(f"Run: conda activate {project_name}")
return
except FileNotFoundError:
pass
# Look for venv environment
possible_venv_paths = [
project_dir / "{project_name}_env",
project_dir / "venv",
project_dir / ".venv"
]
for venv_path in possible_venv_paths:
if venv_path.exists():
if os.name == 'nt':
activate_script = venv_path / "Scripts" / "activate.bat"
if activate_script.exists():
os.system(str(activate_script))
return
else:
activate_script = venv_path / "bin" / "activate"
if activate_script.exists():
print(f"Run: source {{activate_script}}")
return
print("No virtual environment found!")
print("Create one with:")
print(f" conda create --name {project_name} python=3.9")
print(f" or")
print(f" python -m venv {project_name}_env")
if __name__ == "__main__":
activate_environment()
'''
with open(f"activate_{project_name}.py", 'w') as f:
f.write(script_content)
print(f"Universal activator created: activate_{project_name}.py")
print(f"Usage: python activate_{project_name}.py")
# Example usage
create_universal_activator("myproject")
Environment Migration Tools #
Venv to Conda Migrator #
def migrate_venv_to_conda(venv_path, conda_env_name):
"""Migrate packages from venv to conda environment"""
import subprocess
import tempfile
from pathlib import Path
venv_path = Path(venv_path)
# Export venv requirements
if os.name == 'nt':
pip_path = venv_path / 'Scripts' / 'pip.exe'
else:
pip_path = venv_path / 'bin' / 'pip'
if not pip_path.exists():
print(f"Error: pip not found in {venv_path}")
return False
# Create temporary requirements file
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
temp_req_file = f.name
try:
# Export requirements
subprocess.run([str(pip_path), 'freeze'],
stdout=open(temp_req_file, 'w'), check=True)
# Create conda environment
subprocess.run(['conda', 'create', '--name', conda_env_name,
'python=3.9', '-y'], check=True)
# Install packages
subprocess.run(['conda', 'activate', conda_env_name, '&&',
'pip', 'install', '-r', temp_req_file],
shell=True, check=True)
print(f"Migration completed: venv -> conda ({conda_env_name})")
return True
except subprocess.CalledProcessError as e:
print(f"Migration failed: {e}")
return False
finally:
os.unlink(temp_req_file)
Summary #
These Python virtual environment setup scripts solve common conda vs venv issues through automation. Use the detection scripts to diagnose problems, the setup scripts to create environments consistently, and the repair tools when your Python virtual environment not working conda vs venv setup needs fixing.
Copy these code examples and customize them for your specific workflow. The universal scripts work across Windows, macOS, and Linux, providing reliable virtual environment management regardless of your platform or tool choice.