Skip to content

Instantly share code, notes, and snippets.

@gwpantazes
Created June 25, 2019 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gwpantazes/e6b24e0dd90f1acda9431e37a8c0ff2c to your computer and use it in GitHub Desktop.
Save gwpantazes/e6b24e0dd90f1acda9431e37a8c0ff2c to your computer and use it in GitHub Desktop.
Check if you are in a Python Virtual Environment
# 100% surefire way to detect a virtual environment: Check for the real_prefix system attribute.
echo $(python <<EOF
import sys
if(hasattr(sys, 'real_prefix')):
print("Yes, you are in a virtual environment. (" + getattr(sys, 'real_prefix') + ")")
else:
print("No, you are not in a virtual environment.")
EOF
)
# Not-as-good way, documented for posterity. See https://stackoverflow.com/a/1883251/2291928
# The $VIRTUAL_ENV environment variable gets set by the virtualenv active script,
# but that's not 100% reliable since you can start python in a virtual environment manually without activate.
# echo $VIRTUAL_ENV
@gkotian
Copy link

gkotian commented Aug 25, 2021

Thanks for the script. However, it doesn't seem to work with new Python versions and latest virtualenv. For my needs, I have modified it to:

echo $(python <<EOF
import sys
if sys.prefix == sys.base_prefix:
    print("No, you are not in a virtual environment.")
else:
    print("Yes, you are in a virtual environment.")
EOF
)

To ensure support for older versions as well, look at https://stackoverflow.com/a/1883251/793930.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment