26.9. Using Python Virtual Environments
Prev | Chapter 26. Miscellaneous Functionality | Next

## 26.9. Using Python Virtual Environments

Python supports lightweight "virtual environments" (usually abbreviated virtualenv) which allow encapsulation / isolation of package dependencies for a project. When a Python program is executed in the context of a virtualenv, the paths for package imports are amended so the modules in the virtualenv are preferred. Depending on how the virtualenv was configured, system paths may or may not be used as a fallback (the default is not).

SCons itself works as expected when executed within a virtualenv. However, there may be issues if the project needs to build using external commands written in Python which are installed in the virtualenv, or calls the Python interpreter to run a script. SCons launches command actions using a special restricted `PATH` setting which the new process uses to find executables. This path is part of the execution environment (see Section 7.3, “Controlling the Execution Environment for Issued Commands”), and by default, does not contain any information about the virtualenv. The result can be commands not found, or scripts executed with the system default copy of Python rather than the virtualenv one, possibly causing incorrect imports. If you encounter this problem, SCons provides a mechanism to more fully integrate with a virtualenv.

Use the `--enable-virtualenv` to import virtualenv-related environment variables to the execution environment (`$ENV`) and to modify the execution environment's `PATH` appropriately to prefer the virtualenv executables and Python interpreter.

To make this setting permanent, you can either:

- Add it to the `SCONSFLAGS` environment variable , or

- Set `SCONS_ENABLE_VIRTUALENV=1` in your environment.

`SCONSFLAGS` is the preferred approach, as it's easier to manage a single variable controlling SCons behavior than multiples. If enabled by environment variable, the special virtualenv behavior can be disabled for the current run using the `--ignore-virtualenv` option.

You can query the state at runtime by calling the `Virtualenv` global function. It returns a path to the virtualenv's home directory, or an empty string if SCons is not running in a virtualenv.

### Note

`Virtualenv` returns a path even if SCons is run from an unactivated virtualenv. A virtualenv does not have to be activated to be used, you only need to use the path to its Python interpreter, but only an activated virtualenv makes available the suitable `PATH` elements for SCons to copy in when `--enable-virtualenv` is used.

Prev | Up | Next
26.8. Declaring Additional Outputs: the `SideEffect` Function | Home | Chapter 27. Using SCons with other build tools