Skip to content

Commit

Permalink
Add function to detect if source terminal is in a virtual env
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexMili committed May 30, 2024
1 parent 37130a9 commit 2a0fa7f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,17 @@ prompt = nameOfYourProject

Note that virtual environment created with `virtualenv` have more keys and the key `prompt` is not present by default in `venv` created environments.

You can also check if the terminal from which the script has been launched is in a virtual env:
```python
if running_from_activated_env() is True:
print("The script is running from a terminal with an activated virtual env")
```

Note that this function check the existence of `VIRTUAL_ENV`. It is set by the activate script, but a virtual env can be used without activation by directly running an executable from the virtual env's bin/ (or Scripts on Windows) directory, in which case `VIRTUAL_ENV` will not be set. Or a non-virtual env Python binary can be executed directly while a virtual env is activated in the shell, in which case `VIRTUAL_ENV` may be set in a Python process that is not actually running in that virtual env.

[Source](https://stackoverflow.com/a/1883251)


## CLI
```console
$ isvirtual
Expand Down
11 changes: 11 additions & 0 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,17 @@ def is_conda() -> bool:
return is_conda


def running_from_activated_env() -> bool:
running = False
try:
os.environ["VIRTUAL_ENV"]
running = True
except Exception:
pass

return running


def _get_prefix() -> str:
return sys.real_prefix if hasattr(sys, "real_prefix") else sys.prefix

Expand Down

0 comments on commit 2a0fa7f

Please sign in to comment.