I’m quite fond of Python’s virtualenv, which facilitates maintenance of separate Python configurations. I’m considering embedding Python into a C++ application and was wondering how the embedded Python would behave with respect to virtual environments.
In particular, I’m intersted in knowing if it’s possible to “select” a virtual environment based on some user-defined setting (e.g. by naming the virtual environment of interest in a configuration file).
The virtualenv documentation includes a Using virtualenv without
bin/pythonsection that hints at how to configure a virtual environment once the interpreter is already running.To avoid hardcoding the path to the
activate_this.pyscript, I use the following snippet:And you can use it like so:
You can fetch the
overridevalue from a configuration file or something instead of from the command-line argument.Note that you can only still use a single virtual environment pre-process.
Note: in contrast with using the interpreter bundled in the virtual environment, you have access to the packages installed for the interpreter you started. For example, when using a globally-installed Python, you will have access to the globally-installed packages.
Also make sure that you use a Python interpreter with a version that matches whatever version you used to create the virtual environment to make sure that the standard library (copied into the virtual environment) version matches the Python interpreter version.