André Caron
André Caron

Reputation: 45294

Virtual environments and embedding Python

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).

Upvotes: 9

Views: 3816

Answers (2)

André Caron
André Caron

Reputation: 45294

The virtualenv documentation includes a Using virtualenv without bin/python section that hints at how to configure a virtual environment once the interpreter is already running.

To avoid hardcoding the path to the activate_this.py script, I use the following snippet:

def resolve_virtual_environment(override=None):
    """Fetch the virtual environment path in the
       process' environment or use an override."""
    path = os.getenv('VIRTUAL_ENV')
    if override:
        path = os.path.join(os.getcwd(), override)
    return path

def activate_virtual_environment(environment_root):
    """Configures the virtual environment starting at ``environment_root``."""
    activate_script = os.path.join(
        environment_root, 'Scripts', 'activate_this.py')
    execfile(activate_script, {'__file__': activate_script})

And you can use it like so:

if __name__ == '__main__':
    # use first argument is provided.
    override = None
    if len(sys.argv) > 1:
        override = sys.argv[1]
    environment_root = resolve_virtual_environment(override)

You can fetch the override value 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.

Upvotes: 5

synthesizerpatel
synthesizerpatel

Reputation: 28056

Yeah, definitely. It's just a matter of where you set the PYTHONPATH to (or what you compile in).

Make sure to check out pythonqt (not to be mistaken for PySide or PyQt .. it goes the other way, building a Python into a Qt C++ app.

Upvotes: 2

Related Questions