Created
March 10, 2020 23:51
-
-
Save andyneff/ee2f7e0e5a9f031267de82d9701f75bc to your computer and use it in GitHub Desktop.
Relocate a virtualenv on windows.
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
| # Usage: | |
| # Move your virtualenv, then | |
| # {virtual env dir}\Scripts\python.exe relocate.py | |
| # TODO: Merge with Linux script | |
| # TODO: Detect and hangle GUI exes | |
| import sys | |
| import os | |
| import glob | |
| import re | |
| from pip._internal.operations.install.wheel import PipScriptMaker | |
| # import pip._vendor.distlib.scripts | |
| virtual_env_dir = os.path.dirname(os.path.dirname(sys.executable)) | |
| virtual_env_dir = os.path.abspath(virtual_env_dir) | |
| script_dir = os.path.join(virtual_env_dir, 'Scripts') | |
| # Patch activate | |
| with open(os.path.join(script_dir, 'activate.bat'), 'r') as fid: | |
| data = fid.read() | |
| data = re.sub(r'set "VIRTUAL_ENV=.*?"\n', 'set "VIRTUAL_ENV=' + virtual_env_dir.replace('\\', r'\\') + '"\n', data) | |
| prompt = os.path.basename(virtual_env_dir) | |
| data = re.sub(r'set "PROMPT=.*? %PROMPT%"\n', 'set "PROMPT=(' + prompt.replace('\\', r'\\') + ') %PROMPT%"\n', data) | |
| with open(os.path.join(script_dir, 'activate.bat'), 'w') as fid: | |
| fid.write(data) | |
| with open(os.path.join(script_dir, 'activate.xsh'), 'r') as fid: | |
| data = fid.read() | |
| data = re.sub(r'$VIRTUAL_ENV = r".*?"\n', '$VIRTUAL_ENV = r"' + virtual_env_dir.replace('\\', r'\\') + '"\n', data) | |
| with open(os.path.join(script_dir, 'activate.xsh'), 'w') as fid: | |
| fid.write(data) | |
| # Patch Scripts | |
| exes = glob.glob(os.path.join(script_dir, '*.[eE][xX][eE]')) | |
| scripts_to_generate = [] | |
| for exe in exes: | |
| path, filename = os.path.split(exe) | |
| if filename.lower() == 'python.exe': | |
| continue | |
| elif filename.lower() == 'pythonw.exe': | |
| continue | |
| filename, _ = os.path.splitext(filename) | |
| with open(exe, 'rb') as fid: | |
| data = fid.read() | |
| data = data[-1000:] | |
| data = data.split(b'\n') | |
| for d in data: | |
| if d.startswith(b'from '): | |
| # print(d.decode()) | |
| module, func = re.search("from (.*) import (.*)", d.decode()).groups() | |
| break | |
| scripts_to_generate.append(f'{filename} = {module}:{func}') | |
| maker = PipScriptMaker(None, script_dir) | |
| maker.clobber = True | |
| maker.variants = {''} | |
| maker.set_mode = True | |
| # print(scripts_to_generate) | |
| generated_console_scripts = maker.make_multiple(scripts_to_generate) | |
| # print(generated_console_scripts) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment