Skip to content

Instantly share code, notes, and snippets.

@oyale
Created December 19, 2022 19:07
Show Gist options
  • Save oyale/f5aafbbc2b693c70cf656c0f1434ae9f to your computer and use it in GitHub Desktop.
Save oyale/f5aafbbc2b693c70cf656c0f1434ae9f to your computer and use it in GitHub Desktop.
A dead-simple script to perform bulk operations in all python virtualenvs installed
#! /bin/python
"""
A dead-simple script to perform bulk operations in all python virtualenvs installed
"""
import argparse
import os
import subprocess
import glob
# Find out the pyenv conf dir
try:
result = subprocess.run(["pyenv", "root"], stdout=subprocess.PIPE)
except FileNotFoundError:
print("pyenv is not installed or not in the PATH")
exit()
else:
pyenv_root = result.stdout.decode().strip()
# Declare and parse valid arguments
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--upgrade-pip", help="Upgrade the pip package manager", action="store_true"
)
parser.add_argument("--install-module", help="Install a python module", type=str)
parser.add_argument("--upgrade-module", help="Upgrade a python module", type=str)
parser.add_argument("--uninstall-module", help="Upgrade a python module", type=str)
parser.add_argument(
"--list-venvs", help="List all virtual environments", action="store_true"
)
args, unknown = parser.parse_known_args()
module_command = args.install_module or args.upgrade_module or args.uninstall_module
if unknown or (not any([args.upgrade_pip, args.list_venvs]) and not module_command):
parser.print_help()
exit()
else:
home_directory = pyenv_root + "/versions/**/*/"
# Logic for handling every case
if args.upgrade_pip:
print("### Upgrading pip in all virtualenvs...")
path = "python"
command = " -m pip install --upgrade pip"
elif module_command:
path = "pip"
if args.install_module:
command = " install " + args.install_module
if args.upgrade_module:
command = " install " + args.upgrade_module + " --upgrade"
if args.uninstall_module:
command = " uninstall " + args.install_module
print("###" + command + " module in all virtualenvs...")
elif args.list_venvs:
print("### Listing virtualenvs...")
virtualenv_dir = os.path.join(home_directory, path)
print(glob.glob(virtualenv_dir))
exit()
virtualenv_dir = os.path.join(home_directory, path)
virtualenvs = [d for d in glob.glob(virtualenv_dir) if os.path.isfile(d)]
# Iterate through the virtual environments and perform the specified action in each one
for virtualenv in virtualenvs:
print("### Entering " + virtualenv)
try:
print(subprocess.run(virtualenv + command, shell="True"))
if args.upgrade_pip:
print("### pip updated:")
print(subprocess.run(virtualenv + " -V", shell="True"))
print()
print()
print()
except FileNotFoundError:
# pyenv is not installed or not in the PATH
print(path + " is not available at " + home_directory)
exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment