Created
May 16, 2024 10:37
-
-
Save pepoluan/971225f4dbc50349d5028090a31ab9e6 to your computer and use it in GitHub Desktop.
Self-creating a virtualenv with required modules
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 subprocess | |
import sys | |
import tempfile | |
from pathlib import Path | |
try: | |
### PERFORM IMPORTS OF NEEDED MODULE IN THIS try: BLOCK | |
from rich.traceback import install as rtb_install | |
rtb_install(show_locals=True) | |
import ruamel.yaml as ryaml | |
from rich.console import Console | |
CONSOLE = Console(width=79) | |
except (ImportError, ModuleNotFoundError): | |
print("Some needed Python modules are not found; creating a virtualenv...", file=sys.stderr, flush=True) | |
with tempfile.TemporaryDirectory(prefix="venv-", dir=Path("~").expanduser()) as tdir: | |
sh_args = ( | |
"{exe} -m venv {tdir};" | |
". {tdir}/bin/activate;" | |
### EDIT THE FOLLOWING LINE AS NEEDED | |
"python -m pip install --require-virtualenv --disable-pip-version-check --quiet rich ruamel.yaml;" | |
"python {args};" | |
).format( | |
exe=sys.executable, | |
tdir=tdir, | |
args=" ".join( | |
f"'{a}'" for a in sys.argv | |
) | |
) | |
# WARNING: DO NOT use os.exec() here because we want to do cleanup afterwards. | |
# Using os.exec() terminates this script immediately making the TemporaryDirectory context manager | |
# not trigger, resulting in a leftover temp dir. | |
result = subprocess.run( | |
["bash", "-c", sh_args] | |
) | |
print("\nvirtualenv done, cleaning up...", file=sys.stderr, flush=True) | |
sys.exit(result.returncode) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment