Search code examples
pythonvirtualenvpython-venv

Check whether directory is a virtualenv


I'm looking for a way to test whether a directory is a virtualenv or not, e.g. by checking the existence or contents of key files inside the directory.

The purpose of this is that I want to create a script which manages virtualenvs for me and I want to prevent it from removing a directory which is not actually a virtualenv (which could e.g. happen if I used tab completion to choose the virtualenv and was trigger-happy).

Is there some standard way to detect whether a directory has been initialized as a virtualenv by virtualenv? I'm ok with a solution which only works with the newest versions of virtualenv.

My current solution is the check for the existence of the two paths bin/python and bin/activate.


Solution

  • Check for the presence of a pyvenv.cfg file.

    The documentation says:

    Running [the venv command] creates the target directory (creating any parent directories that don’t exist already) and places a pyvenv.cfg file in it with a home key pointing to the Python installation from which the command was run

    This seems to be valid from Python 3.5.9 to at least 3.13.

    Note that the proposed solution of checking for bin/python and bin/activate does not work on Windows, where you would have to check for Scripts instead of bin.