Skip to content

Instantly share code, notes, and snippets.

@kk6
Last active March 28, 2017 15:27
Show Gist options
  • Save kk6/fb2ac5b1d56f4fe449aae6ef8d97d553 to your computer and use it in GitHub Desktop.
Save kk6/fb2ac5b1d56f4fe449aae6ef8d97d553 to your computer and use it in GitHub Desktop.
Pythonのバージョン上げた後にvirtualenv更新するやつ(Python3.5以上で動作)
import os
import subprocess
IGNORE = ['i', 'dont','wanna','update', 'these']
VENVS_DIR = os.path.join(os.path.expanduser('~'), '.virtualenvs')
def get_venvs():
p = subprocess.run("source $(which virtualenvwrapper.sh) && lsvirtualenv -b",
shell=True, stdout=subprocess.PIPE)
return [v.decode('utf8') for v in p.stdout.rstrip().split(b'\n')]
def find_broken_pythons(venvs):
broken_pythons = {}
for venv in venvs:
if venv in IGNORE:
continue
venv_dir = os.path.join(VENVS_DIR, venv)
venv_python = os.path.join(venv_dir, 'bin/python')
try:
subprocess.run([venv_python, '-V'], stdout=subprocess.DEVNULL, check=True)
except subprocess.CalledProcessError:
broken_pythons[venv] = venv_dir
return broken_pythons
def remove_broken_symlinks(broken_pythons):
for venv, venv_dir in broken_pythons.items():
for root, dirs, files in os.walk(venv_dir):
for f in files:
path = os.path.join(root, f)
if os.path.islink(path) and not os.path.exists(os.readlink(path)):
os.unlink(path)
def create_virtualenvs(broken_pythons):
for venv, venv_dir in broken_pythons.items():
bin_dir = os.path.join(venv_dir, 'bin')
python2 = False
for root, dirs, files in os.walk(bin_dir):
if 'python2' in files:
python2 = True
if python2:
subprocess.call('virtualenv {}'.format(venv_dir), shell=True)
else:
subprocess.call('virtualenv {} -p python3'.format(venv_dir), shell=True)
if __name__ == '__main__':
venvs = get_venvs()
broken_pythons = find_broken_pythons(venvs)
remove_broken_symlinks(broken_pythons)
# TODO: Link again the unlinked object in case of error
create_virtualenvs(broken_pythons)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment