Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if Python venv is active in Windows?

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?

like image 835
senox13 Avatar asked Jul 19 '19 21:07

senox13


People also ask

How do I know if Python VENV is activated?

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.


1 Answers

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

like image 92
senox13 Avatar answered Oct 13 '22 15:10

senox13