I am looking for a way, from within either Windows CMD or Powershell, to check if a Python virtual environment has been activated. In Bash, it is possible to use this conditional to check if a venv is active.
if [[ "$VIRTUAL_ENV" != "" ]]
I've also seen this done in Bash, and I could probably get it to work on Windows, but it feels like a hack and, as much as we all like a good hack, I feel like there ought to be a better way.
PYTHON_ENV=$(python -c "import sys; sys.stdout.write('1') if hasattr(sys, 'real_prefix') else sys.stdout.write('0')")
Is there any documented, straightforward way to do this?
Check the $VIRTUAL_ENV environment variable. The $VIRTUAL_ENV environment variable contains the virtual environment's directory when in an active virtual environment. Once you run deactivate / leave the virtual environment, the $VIRTUAL_ENV variable will be cleared/empty.
Of course I figured out a way to do this shortly after asking the question here, but I'll post this as an answer here since I couldn't find this info anywhere else on the site. As expected, Powershell (and probably CMD, though I didn't test it myself) gets an environment variable set, $VIRTUAL_ENV
, when a virtual environment is active. This can be easily tested for in a Powershell script with the following conditional:
if (Test-Path env:VIRTUAL_ENV) {...
Hopefully this helps someone out there
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With