Virtual Environments and Python Implementation

I really love Python virtualenv, which makes it easier to maintain individual Python configurations. I am considering introducing Python into a C ++ application and wondered how embedded Python will work in relation to virtual environments.

In particular, I am interested in knowing whether it is possible to “select” a virtual environment based on certain user settings (for example, by naming the virtual environment of interest in the configuration file).

+5
source share
2 answers

The virtualenv documentation includes Using virtualenv withoutbin/python , which hints at how to set up a virtual environment after the interpreter is already running.

To avoid hard coding the activate_this.pyscript path , 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 this:

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 get the value overridefrom the configuration file or something instead of the command line argument.

Please note that you can use only one preliminary process for one virtual environment.

Note : unlike using the interpreter in a virtual environment, you have access to the packages installed for the running interpreter. For example, if you use globally installed Python, you will have access to globally installed packages.

, Python , , , , ( ) Python.

+3

, . , PYTHONPATH ( , ).

pythonqt ( PySide PyQt.. , Python Qt ++.

0

All Articles