Created
July 28, 2023 05:41
-
-
Save Borillion/ab6e8ab86025dd34b850a1e866c71185 to your computer and use it in GitHub Desktop.
This code creates a virtualenv environment in the directory specified by the -d or --env-dir command-line argument. If the directory does not exist, it will be created if the -c or --create option is used..
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
import shutil | |
import subprocess | |
import argparse | |
# Set up command-line argument parser | |
parser = argparse.ArgumentParser(description='Set up a virtual environment.') | |
parser.add_argument('--env-dir', '-d', type=str, required=True, | |
help='Directory where the virtual environment should be set up.') | |
parser.add_argument('--create', '-c', action='store_true', | |
help='Create the directory if it does not exist.') | |
# Parse command-line arguments | |
args = parser.parse_args() | |
virtualenv_dir = args.env_dir | |
# Check if the directory exists, create it if not and --create flag is passed | |
if args.create and not os.path.exists(virtualenv_dir): | |
os.makedirs(virtualenv_dir) | |
# Find the path to the virtualenv command | |
virtualenv_command = shutil.which('virtualenv') | |
if virtualenv_command is None: | |
print("Error: virtualenv is not installed. Please install it before running this script.") | |
sys.exit(1) | |
# Create the virtual environment | |
print("Creating virtualenv") | |
subprocess.check_call([virtualenv_command, virtualenv_dir]) | |
# Get the Python version | |
python_version = f"{sys.version_info.major}.{sys.version_info.minor}" | |
print(f"System python version detected: {python_version}") | |
# Get the Python interpreter | |
python_exe = sys.executable | |
print("Entering virtualenv") | |
venv_activate = virtualenv_dir + "/bin/activate_this.py" | |
venv_python = virtualenv_dir + "/bin/python" | |
exec(compile(open(venv_activate, "rb").read(), venv_activate, 'exec'), dict(__file__=venv_activate)) | |
# Upgrade pip in the virtual environment | |
subprocess.check_call([venv_python, '-m', 'ensurepip', '--upgrade']) | |
subprocess.check_call([venv_python, '-m', 'pip', 'install', '--upgrade', 'pip']) | |
### Put the script you want to load and run below | |
### or exec(open('script1.py').read()) | |
### or import script1 ; script1.some_function() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment