Skip to content

Instantly share code, notes, and snippets.

@WingTillDie
Last active July 16, 2023 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WingTillDie/e086449a91345a21b6eb4c2e9f6ad5cf to your computer and use it in GitHub Desktop.
Save WingTillDie/e086449a91345a21b6eb4c2e9f6ad5cf to your computer and use it in GitHub Desktop.
Rename Python venv
#!/usr/bin/env python3
#import argparse
import subprocess
import sys
import argparse
parser = argparse.ArgumentParser(prog='rename-venv.py',
description='cd <venv>/.., then run this script'
)
parser.add_argument('old_venv_name')
parser.add_argument('new_venv_name')
args = parser.parse_args()
sh_script = '''
old_venv_name="$1"
new_venv_name="$2"
remove_pycache(){
pycache_dirs=$(find "$old_venv_name" -name __pycache__ -type d)
echo "pycache_dirs" | xargs rm -rf
}
#remove_pycache
filenames=$(fgrep "$old_venv_name" "$old_venv_name" -rl)
# It will also rename the text in binary files (e.g. __pycache__/)
sed -i -e "s|""$old_venv_name""|""$new_venv_name""|g" $filenames
mv "$old_venv_name" "$new_venv_name"
'''
arguments = [
args.old_venv_name,
args.new_venv_name
]
def run_sh_script(sh_script, arguments):
command = ['sh', '-c', sh_script] + [sys.argv[0]] + arguments
p = subprocess.run(command, check=True, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
stdout = p.stdout.decode()
stderr = p.stderr.decode()
return stdout, stderr
stdout, stderr = run_sh_script(sh_script, arguments)
print(stdout, end='')
print(stderr, file=sys.stderr, end='')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment