VirtualEnvOnDemand (version 6.0.0)
index
/home/media/projects/VirtualEnvOnDemand/VirtualEnvOnDemand/__init__.py

VirtualEnvOnDemand contains two primary parts:
 
 * Managing Environments *
 
    VirtualEnvOnDemand provides a simple means for an application or series of applications to create a persistent OR temporary
      virtual environment (virtualenv), install packages within that environment, activate it, etc.
 
 * On-Demand importing *
 
    VirtualEnvOnDemand also provides an "on demand" importer, which allows you to automatically install providing packages
     when imports fail
 
Using VirtualEnvOnDemand allows you to be explicit and pythonify your virtualenv deployment and required packages,
 and not rely on a "black box" of the target system to provide your deps, nor are you forced to couple creating/transferring 
 a virtualenv with your program.
 
It also allows you to easily share scripts/applications with others, without requiring them to have any dependencies (other than virtualenv)
 installed on their system. They also do not need to know how to create virtualenvs, rely on them being active, etc.

 
Package Contents
       
CreateEnv
GlobalEnv
InstallPackages
PersistentEnv
VirtualEnvInfo
exceptions
utils

 
Classes
       
builtins.Exception(builtins.BaseException)
VirtualEnvOnDemand.exceptions.PipInstallFailed
builtins.object
VirtualEnvOnDemand.VirtualEnvInfo.VirtualEnvInfo

 
class PipInstallFailed(builtins.Exception)
    PipInstallFailed - Exception raised when pip fails to install a list of packages
 
 
Method resolution order:
PipInstallFailed
builtins.Exception
builtins.BaseException
builtins.object

Methods defined here:
__init__(self, returnCode=None, reqFileContents='')
Create a PipInstallFailed exception, building a message from some pieces of information
 
    @param returnCode <int> - Return code of subprocess, or None if undetermined
    @param reqFileContents <str> - String of requirements file to reproduce error

Data descriptors defined here:
__weakref__
list of weak references to the object (if defined)

Methods inherited from builtins.Exception:
__new__(*args, **kwargs) from builtins.type
Create and return a new object.  See help(type) for accurate signature.

Methods inherited from builtins.BaseException:
__delattr__(self, name, /)
Implement delattr(self, name).
__getattribute__(self, name, /)
Return getattr(self, name).
__reduce__(...)
helper for pickle
__repr__(self, /)
Return repr(self).
__setattr__(self, name, value, /)
Implement setattr(self, name, value).
__setstate__(...)
__str__(self, /)
Return str(self).
with_traceback(...)
Exception.with_traceback(tb) --
set self.__traceback__ to tb and return self.

Data descriptors inherited from builtins.BaseException:
__cause__
exception cause
__context__
exception context
__dict__
__suppress_context__
__traceback__
args

 
class VirtualEnvInfo(builtins.object)
     Methods defined here:
__getitem__(self, name)
__init__(self, virtualenvDirectory, sitePackagesDirectory='')
@param virtualenvDirectory <str> - Path to the root of the virtualenv
@param sitePackagesDirectory <str> - Path to the site packages directory (goes into PYTHONPATH)
 
If virtualenvDirectory is provided, sitePackagesDirectory will be calculated with default expected values.
 
This object should be considered read-only. If you need to modify values, you must create a new object.
validate(self)
validate - Validate that the virtualenv exists in the expected way.
 
@raises ValueError - With message indicating the reason for failure
 
@return <bool> - True

Static methods defined here:
getBinDir(virtualenvDirectory)
getBinDir - Gets the "bin" dir of a virtualenv
    i.e. the directory that contains executables.
 
NOTE: This is overridden on import with the platform-specific version.
 
 
@param virtualenvDirectory <str> - The path to the root directory of the virtualenv
 
@return <str> - Path to the "bin" directory of the virtualenv
getPipBin(virtualenvDirectory)
getPipBin - Get the path to the pip executable within a virtualenv
 
NOTE: This is overridden on import with the platform-specific version.
 
 
@param virtualenvDirectory <str> - The path to the root directory of the virtualenv
 
@return <str> - Path to the "pip" executable associated with the virtualenv
getPythonBin(virtualenvDirectory)
getPythonBin - Get the path to the virtualenv python executable
 
NOTE: This is overridden on import with the platform-specific version.
 
 
@param virtualenvDirectory <str> - The path to the root directory of the virtualenv
 
@return <str> - Path to the "python" executable associated with the virtualenv
getSitePackagesDirectory(virtualenvDirectory)
getSitePackagesDirectory - Get the site packages directory associated with a virtualenv.
 
NOTE: This is overridden on import with the platform-specific version.
 
@param virtualenvDirectory <str> - The path to the root directory of the virtualenv
 
@return <str> - Path to the "site-packages" directory of the virtualenv

Data descriptors defined here:
sitePackagesDirectory
virtualenvDirectory

 
Functions
       
activateEnv(venv)
activateEnv - Activates a virtualenv (allows you to import installed modules).
 
@param venv <str/VirtualEnvInfo> - A path to the root of a virtualenv, or a VirtualEnvInfo.VirtualEnvInfo object (Like from VirtualEnvInfo.getInfoFromVirtualEnv)
 
@raises - TypeError - if venv is not correct type
@raises - ValueError - if venv is not a usable virtual environment.
 
@return <str> - The path of the site-packages directory which as added to the python import path.
createEnv(packages=None, parentDirectory=None, name=None, stdout=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>, stderr=<_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>, deleteOnClose=True, activateEnvironment=True)
createEnv - Creates a temporary virtual environment and installs the required modules for the current running application.
    You can use this, for example, to "recover" from a failed import by installing the software on demand.
 
    @param packages - Describes the required packages. Takes one of the following forms:
 
        String - Directly becomes contents of requirements.txt file to be ingested by pip
        List   - A list/tuple/set of package names (optionally including version requirements, e.x. MyPkg==1.2.3)
        Dict   - A dictionary of package names to versions. If no value is present, the latest will be fetched.
 
    @param parentDirectory <str> - Parent directory of the directory which will be created to hold the temporary environment and packages. Defaults to tempfile.tempdir
 
    @param name <str> - If provided, will use this as the virtualenv name. Otherwise, a random name will be generated. This should not contain any directories, use #parentDirectory to specify the directory.
 
    @param stdout <iostream/None> - Stream to be used as stdout for installation. Default is sys.stdout. Use "None" to swallow output.
 
    @param stderr <iostream/None> - Stream to be used as stderr for installation. Default is sys.stderr. Use "None" to swallow output.
 
    @param deleteOnClose <bool> - If True (Default), this temporary environment and packages will be erased after program terminates. Note, this cannot trap everything (e.x. SIGKILL).
 
    @param activateEnvironment <bool> Default True, If True, this virtualenv will immediately be activated (so you can import installed packages)
 
    @return - On success, returns a VirtualEnvInfo object, which can be used as a dict with the following fields:
        {
            'virtualenvDirectory'   : Absolute path to the root virtualenv directory
            'sitePackagesDirectory' : Absolute path to the site-packages directory within
            'requirements.txt'      : Full generated requirements.txt file used for pip installation
        }
 
@raises - 
    VirtualEnvOnDemand.exceptions.PipInstallFailed -  if cannot install packages
    ValueError - If parent directory does not exist.
    Others (Exception, etc)                        -  If permissions problem to write to specified directory, etc
createEnvIfCannotImport(importName, packages, parentDirectory=None, stdout=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>, stderr=<_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>, deleteOnClose=True)
createEnvIfCannotImport - Tries to import a given name, and if fails, creates a temporary env and installs given packages and tries again.
 
@see createEnv for most params.
 
@param importName - Name of module to import
 
@raises - 
    VirtualEnvOnDemand.exceptions.PipInstallFailed -  if cannot install packages
    ImportError                                    -  if cannot import even after successful installation of the packages.
    Others (Exception, etc)                        -  If permissions problem to write to specified directory, etc
 
@return - None if no env was created, otherwise the return VirtualEnvInfo object from the createEnv call. @see createEnv
enableOnDemandImporter(tmpDir=None, deferSetup=True, noRetryFailedPackages=True)
enableOnDemandImporter - Calling this method turns on the "on demand" importer. A temporary global env is created, and all failed imports will attempt an installation.
 
   @param tmpDir <str/None> - Temporary directory to use. A subdirectory will be created within this. Defaults to tempfile.gettempdir()
   @param deferSetup <bool> - If True (default), defers setup (which can take a couple seconds) until the first failed import or attempted install.
                                Setup takes a couple seconds. Use this to always enable on-demand importer, but give advantage if all modules are present.
                                If False, the ondemand virtualenv will be setup right-away. If you are using this in a multi-threaded environment, this should be set to False.
   @param noRetryFailedPackages <bool> - If True (default), a package which fails to download will not be retried. This is a performance savings. This should generally always be True,
                                           unless you are using VirtualEnvOnDemand to have a running process written to work with an unreleased module to prevent a restart or something similar.
ensureImport(importName, venvDir, packageName=None, stdout=None, stderr=None)
ensureImport - Try to import a module, and upon failure to import try to install package into provided virtualenv
 
@param importName <str> - The name of the module to import
@param venvDir <str/VirtualEnvInfo> - The path to a virtualenv, likely created by createEnv or the global env (fetched via getGlobalVirtualEnvInfo()).
@param packageName <str/None> - If the package name differs from the import name (like biopython package provides "Bio" module), install this package if import fails. This may contain version info (like AdvancedHTMLParser>6.0)
@param stdout <stream/None> - Stream to use for stdout as package info, or None to silence. Default None. NOTE: This differs from elsewhere where sys.stdout is default.
@param stderr <stream/None> - Stream to use for stderr as package info, or None to silence. Default None. NOTE: This differs from elsewhere where sys.stderr is default.
 
@return - The imported module
 
@raises - ImportError if cannot import.
 
    NOTE: With this method, PipInstallFailed will be intercepted and ImportError thrown instead, as this is intended to be a drop-in replacement for "import" when the package name differs.
ensureImportGlobal(importName, packageName=None, stdout=None, stderr=None)
ensureImportGlobal - Try to import a module, and upon failure to import try to install package into global virtualenv. This assumes that enableOnDemandImporter has already been called.
 
@param importName <str> - The name of the module to import
@param packageName <str/None> - If the package name differs from the import name (like biopython package provides "Bio" module), install this package if import fails. This may contain version info (like AdvancedHTMLParser>6.0)
@param stdout <stream/None> - Stream to use for stdout as package info, or None to silence. Default None. NOTE: This differs from elsewhere where sys.stdout is default.
@param stderr <stream/None> - Stream to use for stderr as package info, or None to silence. Default None. NOTE: This differs from elsewhere where sys.stderr is default.
 
@return - The imported module
 
@raises - ImportError if cannot import.
 
    NOTE: With this method, PipInstallFailed will be intercepted and ImportError thrown instead, as this is intended to be a drop-in replacement for "import" when the package name differs.
getGlobalVirtualEnvInfo()
getGlobalVirtualEnvInfo - Returns the VirtualEnvInfo object representing the global environment, or None if not setup.
 
If not setup, call enableOnDemandImporter() to add the hook and create the "global" env.
 
@return VirtualEnvInfo representing global env, or None if enableOnDemandImporter has not been called.
getInfoFromVirtualEnv(venvPath, validate=True)
getInfoFromVirtualEnv - Gets a VirtualEnvInfo object from a given path.
 
@param venvPath <str> - The root of a virtualenv
@param validate <bool> Default True - If True, will validate that the virtualenv is usable.
 
@raises - if validate is True, @see VirtualEnvInfo.validate
installPackages(packages, venvDir, stdout=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>, stderr=<_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>)
installPackages - Installs packages into a created virtual environment
 
    @param packages - Describes the required packages. Takes one of the following forms:
 
        String - Directly becomes contents of requirements.txt file to be ingested by pip
        List   - A list/tuple/set of package names (optionally including version requirements, e.x. MyPkg==1.2.3)
        Dict   - A dictionary of package names to versions. If no value is present, the latest will be fetched.
 
    @param venvDir <str/VirtualEnvInfo> - Path to a created virtualenv directory. This should be the 'virtualenvDirectory' key from the return of createEnv, or just the VirtualEnvInfo object itself will work.
    @param stdout <iostream/None> - Stream to be used as stdout for installation. Default is sys.stdout. Use "None" to swallow output.
    @param stderr <iostream/None> - Stream to be used as stderr for installation. Default is sys.stderr. Use "None" to swallow output.
 
    @return - The generated requirements.txt used to install packages.
 
    @raises - 
        VirtualEnvOnDemand.exceptions.PipInstallFailed -  if cannot install packages
        VirtualEnvOnDemand.exceptions.VirtualEnvDoesNotExist - If given venvDir does not exist
        Others (Exception, etc)                        -  If permissions problem to write to specified directory, etc
setGlobalVirtualEnv(venv, enableOnDemandImporter=True)
setGlobalVirtualEnv - Sets the global virtualenv to be used by the on demand importer.
 
@param venv <str/VirtualEnvInfo> - Either the path to the root of the virtualenv, or a VirtualEnvInfo (like from getInfoFromVirtualEnv)
@param enableOnDemandImporter <bool> Default True - If True, will enable the on demand importer right away.
 
@return <VirtualEnvInfo> - The global env
setupAndActivateEnv(parentDirectory, name, packages, myVersion=None, forceInstallPackages=False, enableOnDemandImporter=False, printDebug=False)
setupAndActivateEnv - 
 
    @param parentDirectory <str> - This is the directory wherein the virtualenv will be created
    @param name <str> - This is the name of the virtualenv root folder
    @param packages <list/dict/str> - A list of packages to install. You can use pip modifiers, like '==' and '<'. May be any of the following:
 
        List   - A list/tuple/set of package names (optionally including version requirements, e.x. MyPkg==1.2.3)
        Dict   - A dictionary of package names to versions. If no value is present (i.e. evaluates to False, like '' or None), the latest will be fetched.
        String - Directly becomes contents of requirements.txt file to be ingested by pip
 
      Note: if the virtualenv exists already, updates to this field will go unnoticed unless 
        "myVersion" increases, or "forceInstallPackages" is set. @see #myVersion parameter below.
 
        You can also use  " VirtualEnvOnDemand.installPackages( packages, venvInfo ) "  to force install/update of #packages ,
         where "venvInfo" is the return of this function.
        @see #VirtualEnvOnDemand.InstallPackages.installPackages
 
    @param myVersion <str/int> - Any sort of version string. You can use __version__ from your module if you so please. Use None to disable.
 
        When defined, this represents your virtualenv's "version".
 
        If you are inheriting an existing virtualenv, and this method is passed a higher #myVersion than is currently marked in the
          virtualenv directory, this method will attempt to install/update any packages as found in #packages.
 
    @param forceInstallPackages <bool> Default False - If True, will attempt to install/update any packages found in #packages every time.
 
        On production and deployed code, you will likely want to leave this as False, as it carries a performence penality with every script invocation
          to check for updates. Instead, bump the value of "myVersion" e.g. from "1.2.0" to "1.2.0.1" or similar, or 
          explicitly call #VirtualEnvOnDemand.InstallPackages.installPackages from an admin servlet, for example.
 
    @param enableOnDemandImporter <bool> Default False - If True, will use this env as the global "on demand" importer. 
        @see #VirtualEnvOnDemand.GlobalEnv.enableOnDemandImporter
 
    @param printDebug <bool> Default False - If True, will print debug messages about what's going on to stderr.
toggleDebug(isDebug)
toggleDebug - Toggle debug messages. Default disabled.
 
@param isDebug <bool> - Whether to enable debug messages or disable them.
 
@return <bool> - The old state of debug
toggleOnDemandImporter(isActive)
toggleOnDemandImporter - Toggle whether the on demand importer (import hook) is active.
 
    If enableOnDemandImporter was not ever called, this has no effect. Otherwise, calling toggleOnDemandImporter(False) will temporarily disable the import hook, until toggleOnDemandImporter(True) is called.
 
    @param isActive <bool> - To temporarily enable/disable the on-demand importer.
 
    @return <bool> - True if a toggle occured, False if no state has changed.
 
    @raises ValueError - If no global virtualenv has been set, either by enableOnDemandImporter or setGlobalVirtualEnv

 
Data
        __all__ = ('createEnv', 'createEnvIfCannotImport', 'enableOnDemandImporter', 'getGlobalVirtualEnvInfo', 'installPackages', 'ensureImport', 'ensureImportGlobal', 'PipInstallFailed', 'VirtualEnvInfo', 'toggleOnDemandImporter', 'getInfoFromVirtualEnv', 'activateEnv', 'setGlobalVirtualEnv', 'setupAndActivateEnv', 'toggleDebug')
__version_tuple__ = (6, 0, 0)