dotfiles.venv package¶
Objectives¶
dotfiles.venv.ipython_config (ipython_config.py):
- Set variables for standard Virtualenv paths in the environment dict
- Define IPython aliases
- Serialize variables and aliases to:
dotfiles.venv.ipython_magics (ipython_magics.py):
- Configure IPython %magic commands
- cd* – change directories (%cdhelp, %cdp, %cdwh, %cdv, %cds, %cdw)
- ds – print dotfiles_status
Configuration¶
Shell¶
For Bash/ZSH, etc/bash/10-bashrc.venv.sh sets:
# ...
_VENV="${__DOTFILES}/etc/ipython/ipython_config.py"
venv() {
$_VENV $@
}
# ...
etc/bash/10-bashrc.venv.sh is sourced by etc/bash/00-bashrc.before.sh, which is sourced by ~/.bashrc (a symlink to ${__DOTFILES}/etc/.bashrc created by bootstrap_dotfiles.sh -S).
IPython¶
To configure IPython with venv, ipython_config.py must be symlinked into ~/.ipython/profile_default (and, optionally, ipython_magics.py into ~/.ipython/profile_default/startup/):
# symlink paths relative to ${__DOTFILES}
__DOTFILES="~/-dotfiles"
# working directory (path to the dotfiles repository)
_WRD=${WORKON_HOME}/dotfiles/src/dotfiles
# created by ``bootstrap_dotfiles.sh -S``
# ln -s ${_WRD} ${__DOTFILES}
# ln -s ${__DOTFILES}/etc/bashrc ~/.bashrc
# ln -s ${_WRD}/etc/ipython/ipython_config.py \
# ${__DOTFILES}/etc/ipython/ipython_config.py
# MANUALLY INSTALL for each IPython profile
IPY_PROFILE="profile_default"
ln -s ${__DOTFILES}/etc/ipython/ipython_config.py \
~/.ipython/${IPY_PROFILE}/ipython_config.py
ln -s ${__DOTFILES}/etc/ipython/ipython_magics.py \
~/.ipython/${IPY_PROFILE}/ipython_magics.py
Submodules¶
dotfiles.venv.ipython_config module¶
- class dotfiles.venv.ipython_config.CdAlias(pathvar, name=None, aliases=None)[source]¶
Bases: dotfiles.venv.ipython_config.CmdAlias
A CmdAlias for cd change directory functions with venv paths (e.g. $_WRD) for Bash, ZSH, IPython, Vim.
- venv.sh bash functions with tab-completion (cdwrd, cdw, cdw<tab>)
- ipython_magics.py: ipython magics (%cdwrd, cdwrd, cdw)
- venv.vim: vim functions (:Cdwrd)
- BASH_ALIAS_TEMPLATE = '{cmd_name} () {{\n # {cmd_name:16} -- cd ${pathvar}\n {bash_func_name} $@\n}}\n'¶
- BASH_CDALIAS_HEADER = '#!/bin/sh\n## venv.sh\n# generated from $(venv --print-bash --prefix=/)\n\n'¶
- BASH_COMPLETION_TEMPLATE = 'complete -o default -o nospace -F {bash_compl_name} {cmd_name}\n'¶
- BASH_FUNCTION_TEMPLATE = '{bash_func_name} () {{\n # {bash_func_name:16} -- cd ${pathvar} /$@\n [ -z "${pathvar}" ] && echo "{pathvar} is not set" && return 1\n cd "${pathvar}"${{@:+"/${{@}}"}}\n}}\n{bash_compl_name} () {{\n local cur="$2";\n COMPREPLY=($({bash_func_name} && compgen -d -- "${{cur}}" ))\n}}\n'¶
- IPYTHON_MAGICS_FILE_HEADER = '\n#!/usr/bin/env ipython\n# dotfiles.venv.ipython_magics\nfrom __future__ import print_function\n"""\nIPython ``%magic`` commands\n\n* ``cd`` aliases\n* ``ds`` (``dotfiles_status``)\n* ``dr`` (``dotfiles_reload``)\n\nInstallation\n--------------\n.. code-block:: bash\n\n __DOTFILES="~/.dotfiles"\n ipython_profile="profile_default"\n ln -s ${__DOTFILES}/etc/ipython/ipython_magics.py \\\n ~/.ipython/${ipython_profile}/startup/ipython_magics.py\n"""\nimport os\ntry:\n from IPython.core.magic import (Magics, magics_class, line_magic)\nexcept ImportError:\n print("ImportError: IPython")\n # Mock IPython for building docs\n Magics = object\n magics_class = lambda cls, *args, **kwargs: cls\n line_magic = lambda func, *args, **kwargs: func\n\n@magics_class\nclass VenvMagics(Magics):\n def cd(self, envvar, line):\n """\n Change directory\n\n Args:\n envvar (str): os.environ variable name\n line (str): path to append to envvar\n """\n prefix = os.environ.get(envvar, "")\n path = os.path.join(prefix, line)\n return self.shell.magic(\'cd %s\' % path)'¶
- IPYTHON_MAGICS_FOOTER = '\n @line_magic\n def cdhelp(self, line):\n """cdhelp() -- list cd commands"""\n for cdfunc in dir(self):\n if cdfunc.startswith(\'cd\') and cdfunc not in (\'cdhelp\',\'cd\'):\n docstr = getattr(self, cdfunc).__doc__.split(\'--\',1)[-1].strip()\n print("%%%-16s -- %s" % (cdfunc, docstr))\n\n @staticmethod\n def _dotfiles_status():\n """\n Print ``dotfiles_status``: venv variables\n """\n env_vars = [\n \'HOSTNAME\',\n \'USER\',\n \'PROJECT_HOME\',\n \'WORKON_HOME\',\n \'VIRTUAL_ENV_NAME\',\n \'VIRTUAL_ENV\',\n \'_USRLOG\',\n \'_TERM_ID\',\n \'_SRC\',\n \'_APP\',\n \'_WRD\',\n \'PATH\',\n \'__DOTFILES\',\n ]\n environ = dict((var, os.environ.get(var)) for var in env_vars)\n environ[\'HOSTNAME\'] = __import__(\'socket\').gethostname()\n for var in env_vars:\n print(\'{}="{}"\'.format(var, "%s" % environ.get(var,\'\')))\n\n @line_magic\n def dotfiles_status(self, line):\n """dotfiles_status() -- print dotfiles_status() ."""\n return self._dotfiles_status()\n\n @line_magic\n def ds(self, line):\n """ds() -- print dotfiles_status() ."""\n return self._dotfiles_status()\n\n @staticmethod\n def _dotfiles_reload():\n """_dotfiles_reload() -- print NotImplemented"""\n print("NotImplemented: dotfiles_reload()")\n\n @line_magic\n def dotfiles_reload(self, line):\n """dotfiles_reload() -- print NotImplemented"""\n return self._dotfiles_reload()\n\n @line_magic\n def dr(self, line):\n """dr() -- print NotImplemented [dotfiles_reload()]"""\n return self._dotfiles_reload()\n\n\ndef main():\n """\n Register VenvMagics with IPython\n """\n import IPython\n ip = IPython.get_ipython()\n ip.register_magics(VenvMagics)\n\n\nif __name__ == "__main__":\n main()\n'¶
- IPYTHON_MAGIC_METHOD_TEMPLATE = '\n @line_magic\n def {ipy_func_name}(self, line):\n """{ipy_func_name} -- cd ${pathvar}/${{@}}"""\n return self.cd(\'{pathvar}\', line)'¶
- VIM_COMMAND_TEMPLATE = '" :{cmd_name} -- {vim_func_name}()\ncommand! -nargs=* {cmd_name} call {vim_func_name}(<f-args>)\n'¶
- VIM_FUNCTION_TEMPLATE = 'function! {vim_func_name}(...)\n" {vim_func_name}() -- cd ${pathvar}/$1\n if a:0 > 0\n let pathname = join([${pathvar}, a:1], "/")\n else\n let pathname = "${pathvar}"\n endif\n execute \'cd\' pathname \n pwd\nendfunction\n'¶
- VIM_HEADER_TEMPLATE = '\n" ### venv.vim\n" # Src: https://github.com/westurner/venv.vim\n\nfunction! Cd_help()\n" cdhelp() -- list cd commands\n :verbose command Cd\nendfunction\ncommand! -nargs=* Cdhelp call Cd_help()\n\n'¶
- __str__()¶
Returns: eval ‘{_to_bash_function()}’ Return type: str
- to_bash_function(include_completions=True)[source]¶
Keyword Arguments: include_completions (bool) – generate inline Bash completions Returns: bash function block Return type: str
- class dotfiles.venv.ipython_config.CmdAlias(cmdstr)[source]¶
Bases: object
- __repr__(name=None)¶
Generate an alias or function for bash/zsh
Keyword Arguments: name (str) – funcname to override default Returns: self.cmdstr (AS-IS) Return type: str
- __str__(name=None)¶
Generate an alias or function for bash/zsh
Keyword Arguments: name (str) – funcname to override default Returns: self.cmdstr (AS-IS) Return type: str
- to_ipython_alias()[source]¶
Generate an alias for IPython
Returns: self.cmdstr (AS-IS) Return type: str
- class dotfiles.venv.ipython_config.Env(*args, **kwargs)[source]¶
Bases: object
OrderedDict of variables for/from os.environ.
- compress_paths(path_, keys=None, keyname=None)[source]¶
Given an arbitrary string, replace absolute paths (starting with ‘/’) with the longest matching Env path variables.
Parameters: path (str) – a path string Returns: path string containing ${VARNAME} variables Return type: str
- classmethod from_environ(environ, verbose=False)[source]¶
Build an Env from a dict (e.g. os.environ)
Parameters: - environ (dict) – a dict with variable name keys and values
- verbose (bool) – whether to be verbose about dict merging
Returns: an Env environment built from the given environ dict
Return type: Env
- ndiff(other_env)[source]¶
Parameters: other_env (Env) – env to compare with Returns: strings from difflib.ndiff Return type: iterable
- osenviron_keys = OrderedDict([('__WRK', '${HOME}/-wrk'), ('__SRC', '${__WRK}/-src'), ('__DOTFILES', '${HOME}/-dotfiles'), ('WORKON_HOME__py27', '${__WRK}/-ve27'), ('WORKON_HOME__py34', '${__WRK}/-ve34'), ('WORKON_HOME_DEFAULT', 'WORKON_HOME__py27'), ('CONDA_ROOT__py27', '${__WRK}/-conda27'), ('CONDA_HOME__py27', '${__WRK}/-ce27'), ('CONDA_ROOT__py34', '${__WRK}/-conda34'), ('CONDA_HOME__py34', '${__WRK}/-ce34'), ('CONDA_ROOT_DEFAULT', 'CONDA_ROOT__py27'), ('CONDA_HOME_DEFAULT', 'CONDA_HOME__py27'), ('CONDA_ROOT', '${__WRK}/-conda27'), ('CONDA_HOME', '${__WRK}/-ce27'), ('WORKON_HOME', '${__WRK}/-ve27'), ('VENVSTR', 'dotfiles'), ('VENVSTRAPP', 'dotfiles'), ('VIRTUAL_ENV_NAME', 'dotfiles'), ('VIRTUAL_ENV', '${WORKON_HOME}/${VIRTUAL_ENV_NAME}'), ('VENVPREFIX', '${VIRTUAL_ENV}'), ('_APP', 'dotfiles'), ('_ETC', '${VIRTUAL_ENV}/etc'), ('_SRC', '${VIRTUAL_ENV}/src'), ('_WRD', '${_SRC}/dotfiles'), ('_BIN', '${VIRTUAL_ENV}/bin'), ('_ETCOPT', '${_ETC}/opt'), ('_HOME', '${VIRTUAL_ENV}/home'), ('_LIB', '${VIRTUAL_ENV}/lib'), ('_PYLIB', '${_LIB}/python2.7'), ('_PYSITE', '${_PYLIB}/site-packages'), ('_MNT', '${VIRTUAL_ENV}/mnt'), ('_MEDIA', '${VIRTUAL_ENV}/media'), ('_OPT', '${VIRTUAL_ENV}/opt'), ('_ROOT', '${VIRTUAL_ENV}/root'), ('_SBIN', '${VIRTUAL_ENV}/sbin'), ('_SRV', '${VIRTUAL_ENV}/srv'), ('_TMP', '${VIRTUAL_ENV}/tmp'), ('_USR', '${VIRTUAL_ENV}/usr'), ('_USRBIN', '${VIRTUAL_ENV}/usr/bin'), ('_USRINCLUDE', '${VIRTUAL_ENV}/usr/include'), ('_USRLIB', '${VIRTUAL_ENV}/usr/lib'), ('_USRLOCAL', '${VIRTUAL_ENV}/usr/local'), ('_USRLOCALBIN', '${VIRTUAL_ENV}/usr/local/bin'), ('_USRSBIN', '${VIRTUAL_ENV}/usr/sbin'), ('_USRSHARE', '${VIRTUAL_ENV}/usr/share'), ('_USRSRC', '${VIRTUAL_ENV}/usr/src'), ('_VAR', '${VIRTUAL_ENV}/var'), ('_VARCACHE', '${_VAR}/cache'), ('_VARLIB', '${_VAR}/lib'), ('_VARLOCK', '${_VAR}/lock'), ('_LOG', '${_VAR}/log'), ('_VARMAIL', '${_VAR}/mail'), ('_VAROPT', '${_VAR}/opt'), ('_VARRUN', '${_VAR}/run'), ('_VARSPOOL', '${_VAR}/spool'), ('_VARTMP', '${_VAR}/tmp'), ('_WWW', '${_VAR}/www'), ('PROJECT_FILES', ''), ('VIMBIN', '/usr/bin/vim'), ('GVIMBIN', '/usr/local/bin/gvim'), ('MVIMBIN', '/usr/local/bin/mvim'), ('GUIVIMBIN', '/usr/local/bin/gvim'), ('VIMCONF', '--servername dotfiles'), ('_EDIT_', '/usr/local/bin/gvim --servername dotfiles --remote-tab-silent'), ('EDITOR_', '/usr/local/bin/gvim --servername dotfiles --remote-tab-silent'), ('_NOTEBOOKS', '${_SRC}/notebooks'), ('_IPYSESKEY', '${_SRC}/.ipyseskey'), ('_IPQTLOG', '${VIRTUAL_ENV}/.ipqt.log'), ('_WRD_SETUPY', '${_WRD}/setup.py'), ('_TEST_', '(cdwrd && python "${_WRD_SETUPY}" test)'), ('_CFG', '${_ETC}/development.ini'), ('_EDITCFG_', '/usr/local/bin/gvim --servername dotfiles --remote-tab-silent ${_ETC}/development.ini'), ('_SHELL_', '(cdwrd && "${_BIN}"/pshell "${_CFG}")'), ('_SERVE_', '(cdwrd && "${_BIN}"/pserve --app-name=main --reload --monitor-restart "${_CFG}")'), ('_SVCFG', '${_ETC}/supervisord.conf'), ('_SVCFG_', ' -c "${_ETC}/supervisord.conf"'), ('__USRLOG', '${HOME}/-usrlog.log'), ('_USRLOG', '${VIRTUAL_ENV}/-usrlog.log')])¶
- osenviron_keys_classic = ('VIMBIN', 'GVIMBIN', 'MVIMBIN', 'GUIVIMBIN', 'VIMCONF', 'EDITOR', 'EDITOR_', 'PAGER', '__WRK', '__DOTFILES', 'PROJECT_HOME', 'WORKON_HOME', 'WORKON_HOME__py27', 'WORKON_HOME__py34', 'VENVPREFIX', 'VENVSTR', 'VENVSTRAPP', '_APP', 'VIRTUAL_ENV_NAME', 'VIRTUAL_ENV', '_SRC', '_ETC', '_BIN', '_CFG', '_LIB', '_LOG', '_MNT', '_OPT', '_PYLIB', '_PYSITE', '_SRV', '_VAR', '_WRD', '_WRD_SETUPY', '_WWW', '__SRC', '__DOCSWWW', '_USRLOG', '__USRLOG', '_TERM_ID', '_TERM_URI')¶
- class dotfiles.venv.ipython_config.IpyAlias(cmdstr, name=None)[source]¶
Bases: dotfiles.venv.ipython_config.CmdAlias
An IPython alias command string which expands to a shell function aliasname() { ... } and handles positional args %s and %l
References
- TODO: IPython docs
- class dotfiles.venv.ipython_config.PrintEnvStderrStep(func=None, **kwargs)[source]¶
Bases: dotfiles.venv.ipython_config.PrintEnvStep
Print env and kwargs to stderr
- stdout = <open file '<stderr>', mode 'w' at 0x7fef3f5f61e0>¶
- class dotfiles.venv.ipython_config.PrintEnvStep(func=None, **kwargs)[source]¶
Bases: dotfiles.venv.ipython_config.Step
Print env and kwargs to stdout
- func(env=None, **kwargs)¶
Default build_*_env Step.func function to print env
Keyword Arguments: - env (Env) – Env object (default: None)
- kwargs (dict) – kwargs dict
Returns: Env: updated Env
- stderr = <open file '<stderr>', mode 'w' at 0x7fef3f5f61e0>¶
- stdout = <open file '<stdout>', mode 'w' at 0x7fef3f5f6150>¶
- class dotfiles.venv.ipython_config.Step(func=None, **kwargs)[source]¶
Bases: object
A build task step which builds or transforms an Env, by calling step.build(env=env, **step.conf)
- DEFAULT_FUNC(env=None, **kwargs)¶
Default build_*_env Step.func function to print env
Keyword Arguments: - env (Env) – Env object (default: None)
- kwargs (dict) – kwargs dict
Returns: Env: updated Env
- build(env=None, **kwargs)[source]¶
Call self.func(env=env, **self.conf.copy().update(**kwargs))
Keyword Arguments: - env (Env) – Env object (default: None)
- kwargs (dict) – kwargs dict
Returns: self.func(env=env, **self.conf.copy().update(**kwargs))
Return type: obj
- build_print_kwargs_env(env=None, **kwargs)[source]¶
Default build_*_env Step.func function to print env
Keyword Arguments: - env (Env) – Env object (default: None)
- kwargs (dict) – kwargs dict
Returns: Env: updated Env
- func(env=None, **kwargs)¶
Default build_*_env Step.func function to print env
Keyword Arguments: - env (Env) – Env object (default: None)
- kwargs (dict) – kwargs dict
Returns: Env: updated Env
- class dotfiles.venv.ipython_config.StepBuilder(**kwargs)[source]¶
Bases: object
A class for building a sequence of steps which modify env
- add_step(func, **kwargs)[source]¶
Add a step to self.steps
Parameters: - func (Step or function or str) – func(env=None, **kwargs)
- kwargs (dict) – kwargs for Step.conf
Keyword Arguments: name (str) – function name (default: None)
Returns: Step: Step object appended to self.steps
- build(*args, **kwargs)[source]¶
Build a list of Envs from self.build_iter(*args, **kwargs) and return the last Env.
Keyword Arguments: debug (bool) – log.debug(env) Returns: Env or None: the last env returned from .build_iter
- build_iter(env=None, show_diffs=True, debug=False)[source]¶
Build a generator of (Step, Env) tuples from the functional composition of StepBuilder.steps given an initial Env (or None).
# pseudocode env_previous = Env() for step in self.steps: (step, env) = step.build(env=env_previous.copy(),**conf) env_previous=env
Keyword Arguments: - env (Env) – initial Env (default: None)
- show_diffs (bool) – show difflib.ndiffs of Envs between steps
- debug (bool)
Yields: tuple – (Step, Env)
- exception dotfiles.venv.ipython_config.StepConfigException[source]¶
Bases: dotfiles.venv.ipython_config.StepException, dotfiles.venv.ipython_config.ConfigException
- class dotfiles.venv.ipython_config.Test_001_lookup(methodName='runTest')[source]¶
Bases: unittest.case.TestCase
- class dotfiles.venv.ipython_config.Test_100_Env(methodName='runTest')[source]¶
Bases: unittest.case.TestCase
- class dotfiles.venv.ipython_config.Test_200_StepBuilder(methodName='runTest')[source]¶
Bases: unittest.case.TestCase
- class dotfiles.venv.ipython_config.Test_250_Venv(methodName='runTest')[source]¶
Bases: unittest.case.TestCase
- class dotfiles.venv.ipython_config.Test_300_venv_build_env(methodName='runTest')[source]¶
Bases: unittest.case.TestCase
test each build step independently
kwargs = {} env = env.copy() buildfunc = build_virtualenvwrapper_env new_env = buildfunc(env=env, **kwargs)
- class dotfiles.venv.ipython_config.Test_500_Venv(methodName='runTest')[source]¶
Bases: unittest.case.TestCase
- class dotfiles.venv.ipython_config.Test_900_Venv_main(methodName='runTest')[source]¶
Bases: unittest.case.TestCase
- class dotfiles.venv.ipython_config.Venv(VENVSTR=None, VENVSTRAPP=None, _Venv__WRK=None, _Venv__DOTFILES=None, WORKON_HOME=None, VIRTUAL_ENV_NAME=None, VENVPREFIX=None, VIRTUAL_ENV=None, _SRC=None, _APP=None, _WRD=None, env=None, from_environ=False, open_editors=False, open_terminals=False, dont_reflect=True, debug=False, show_diffs=False, **kwargs)[source]¶
Bases: object
A virtual environment configuration generator
- build(env=None, VENVSTR=None, VENVSTRAPP=None, VENVPREFIX=None, from_environ=False, dont_reflect=True, debug=False, show_diffs=False)[source]¶
Build Venv Steps with StepBuilder
- call(command)[source]¶
Parameters: command (str) – command to run Returns: output from subprocess.call Return type: str
- configure_ipython(*args, **kwargs)[source]¶
Configure IPython with Venv._configure_ipython and user_aliases from self.aliases.items().
Parameters: - args (list) – args for Venv._configure_ipython
- kwargs (dict) – kwargs for Venv._configure_ipython.
- generate_bash_cdalias()[source]¶
Generate a source-able script for cdalias functions
Yields: str – block of bash script
- generate_bash_env(shell_keyword='export ', shell_quotefunc=<function shell_quote at 0x7fef3c31ede8>, include_paths=True, include_aliases=True, include_cdaliases=False, **kwargs)[source]¶
Generate a source-able script for the environment variables, aliases, and functions defined by the current Venv.
Keyword Arguments: - shell_keyword (str) – shell variable def (default: “export ”)
- include_paths (bool) – Include environ vars in output (default: True)
- include_aliases (bool) – Include aliases in output (default: True)
- include_cdaliases (bool) – Include cdaliases in output (default: False)
- compress_paths (bool) – Compress paths to $VAR (default=False)
Yields: str – block of bash script
- generate_ipython_magics()[source]¶
Generate an ipython_magics.py file for IPython
Yields: str – block of Python code
- generate_vim_cdalias()[source]¶
Generate a source-able vimscript for vim
Yields: str – block of vim script
- static parse_VENVSTR(env=None, VENVSTR=None, VENVSTRAPP=None, VENVPREFIX=None, VIRTUAL_ENV=None, VIRTUAL_ENV_NAME=None, _APP=None, _SRC=None, _WRD=None, _Venv__WRK=None, WORKON_HOME=None, from_environ=False, **kwargs)[source]¶
Get the path to a virtualenv given a VENVSTR
Keyword Arguments: - env (Env)
- VENVSTR (str) – a path to a virtualenv containing / OR just the name of a virtualenv in $WORKON_HOME
- VENVSTRAPP (str)
- VENVPREFIX (str)
- WORKON_HOME (str)
- from_environ (bool) – whether to try and read from os.environ["VIRTUAL_ENV"]
Returns: a path to a virtualenv (for $VIRTUAL_ENV)
Return type: str
- system(cmd=None)[source]¶
Call os.system with the given command string
Parameters: cmd (string) – command string to call os.system with
Raises: - Exception – if cmd is None
- NotImplementedError – if cmd is a tuple
- to_json(indent=None)[source]¶
Parameters: indent (int) – number of spaces with which to indent JSON output Returns: json.dumps(self.to_dict()) Return type: str
- static update_os_environ(venv, environ=None)[source]¶
Update os.environ for the given venv
Parameters: environ (dict) – if None, defaults to os.environ Returns: updated environ dict Return type: dict
- classmethod workon(env=None, VENVSTR=None, VENVSTRAPP=None, **kwargs)[source]¶
Parameters: - VENVSTR (str) – a path to a virtualenv containing / OR just the name of a virtualenv in $WORKON_HOME
- VENVSTRAPP (str) – e.g. dotfiles or dotfiles/docs
- kwargs (dict) – kwargs to pass to Venv (see Venv.__init__)
Returns: an intialized Venv
Return type: Venv
- class dotfiles.venv.ipython_config.VenvJSONEncoder(skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None)[source]¶
Bases: json.encoder.JSONEncoder
- class dotfiles.venv.ipython_config.VenvTestUtils[source]¶
Bases: object
Test fixtures for TestCases and examples
- dotfiles.venv.ipython_config.build_conda_cfg_env(env=None, **kwargs)[source]¶
Configure conda for a specific environment TODO build_venv_config
Parameters: env (Env dict) – dotfiles.venv.ipython_config.Env Returns: env – dotfiles.venv.ipython_config.Env Return type: Env dict
- dotfiles.venv.ipython_config.build_conda_env(env=None, **kwargs)[source]¶
Configure conda27 (2.7) and conda (3.4) with condaenvs in -wrk/-ce27 and -wrk/ce34.
Other Parameters: - __WRK (str) – workspace root ($__WRK, ~/-wrk)
- CONDA_ROOT__py27 (str) – path to conda27 root environment
- CONDA_HOME__py27 (str) – path to conda27 envs (e.g. WORKON_HOME)
- CONDA_ROOT__py34 (str) – path to conda34 root environment
- CONDA_HOME__py34 (str) – path to conda34 envs (e.g. WORKON_HOME)
Keyword Arguments: env (Env dict) – dotfiles.venv.ipython_config.Env
Returns: Return type: Env dict
- dotfiles.venv.ipython_config.build_dotfiles_env(env=None, **kwargs)[source]¶
Configure dotfiles base environment (HOME, __WRK, __SRC, __DOTFILES)
Keyword Arguments: - env (Env dict) – dotfiles.venv.ipython_config.Env
- HOME (str) – home path ($HOME, ~)
- __WRK (str) – workspace path ($__WRK, ~/-wrk)
- __SRC (str) – path to source repos ($__WRK/-src)
- __DOTFILES (str) – current dotfiles path (~/-dotfiles)
Returns: env – dotfiles.venv.ipython_config.Env
Sets:
- HOME
- __WRK
- __SRC
- __DOTFILES
Return type: Env dict
- dotfiles.venv.ipython_config.build_user_aliases_env(env=None, dont_reflect=False, VIRTUAL_ENV=None, _SRC=None, _ETC=None, _CFG=None, PROJECT_FILES=None, **kwargs)[source]¶
Configure env variables and return an OrderedDict of aliases
Parameters: dont_reflect (bool) – Whether to always create aliases and functions referencing $_WRD even if $_WRD doesn’t exist. (default: False) Returns: dict of aliases Return type: OrderedDict
- dotfiles.venv.ipython_config.build_usrlog_env(env=None, _TERM_ID=None, shell='bash', prefix=None, USER=None, HOSTNAME=None, lookup_hostname=False, **kwargs)[source]¶
Build environment variables and configuration like usrlog.sh
Keyword Arguments: - env (Env dict) – dotfiles.venv.ipython_config.Env
- _TERM_ID (str) – terminal identifier string
- shell (str) – shell name (“bash”, “zsh”)
- prefix (str) – a path prefix (e.g. $VIRTUAL_ENV or $PREFIX)
- USER (str) – system username ($USER) for HISTTIMEFORMAT
- HOSTNAME (str) – system hostname (HOSTNAME) for HISTTIMEFORMAT
- lookup_hostname (bool) – if True, HOSTNAME is None, and not env.get(‘HOSTNAME’), try to read HOSTNAME from os.environ and then socket.gethostname().
Returns: Return type: Env dict
Note
Like usrlog.sh, when HISTTIMEFORMAT is set, USER and HOSTNAME must be evaluated.
(When USER and HOSTNAME change, HISTTIMEFORMAT is not updated, and the .history file will contain only the most recent USER and HOSTNAME settings, which are not necessarily the actual USER and HOSTNAME.)
TODO: could/should instead (also) write USER and HOSTNAME to -usrlog.log.
- dotfiles.venv.ipython_config.build_venv_activate_env(env=None, VENVSTR=None, VENVSTRAPP=None, from_environ=False, VENVPREFIX=None, VIRTUAL_ENV=None, VIRTUAL_ENV_NAME=None, _APP=None, _SRC=None, _WRD=None, **kwargs)[source]¶
- dotfiles.venv.ipython_config.build_venv_arg_parser()[source]¶
Returns: optparse.OptionParser: options for the commandline interface
- dotfiles.venv.ipython_config.build_venv_paths_cdalias_env(env=None, **kwargs)[source]¶
Build CdAliases for standard paths
Keyword Arguments: env (Env dict) – Env Returns: env – Env with .aliases extended. Return type: Env dict Note
These do not work in IPython as they run in a subshell. See: dotfiles.venv.ipython_magics.
- dotfiles.venv.ipython_config.build_venv_paths_full_env(env=None, pyver=None, **kwargs)[source]¶
Set variables for standard paths in the environment
Keyword Arguments: - env (Env dict) – dotfiles.venv.ipython_config.Env (default: None (Env()))
- VENVPREFIX (str) – venv prefix path (default: None (VIRTUAL_ENV))
- VENVSTR (str) – name of a VIRTUAL_ENV in WORKON_HOME or path to a VIRTUAL_ENV (default: None)
- VIRTUAL_ENV (str) – path to a VIRTUAL_ENV (default: None)
Returns: Return type: Env dict
Raises: StepConfigException – When not any(( VIRTUAL_ENV, VENVPREFIX, VENVSTR, VENVSTRAPP))
References
- dotfiles.venv.ipython_config.build_virtualenvwrapper_env(env=None, **kwargs)[source]¶
Set WORKON_HOME to WORKON_HOME or WORKON_HOME_DEFAULT
Keyword Arguments: - env (Env dict) – dotfiles.venv.ipython_config.Env
- __WRK (str) – workspace path ($__WRK, ~/-wrk)
- WORKON_HOME_DEFAULT (str) – variable name (default: WORKON_HOME__py27)
- WORKON_HOME__* (str): path to a WORKON_HOME set
Returns: env – dotfiles.venv.ipython_config.Env
Sets:
- WORKON_HOME__py27=’${__WRK}/-ve27’
- WORKON_HOME__py34=’${__WRK}/-ve34’
- WORKON_HOME__*=kwargs.get(WORKON_HOME__*)
- WORKON_HOME_DEFAULT=’WORKON_HOME_py27’
Return type: Env dict
- dotfiles.venv.ipython_config.comment_comment(strblock, **kwargs)[source]¶
Parameters: strblock (str) – string block (possibly containing newlines) Keyword Arguments: kwargs (dict) – kwargs for prepend_comment_char Returns: string with each line prefixed with comment char Return type: str
- dotfiles.venv.ipython_config.get_WORKON_HOME_default(env=None, from_environ=False, default='-ve27', **kwargs)[source]¶
Keyword Arguments: - env (dict) – Env dict to read from (default: None)
- from_environ (bool) – read WORKON_HOME from os.environ
- default (str) – default WORKON_HOME dirname
- __WRK (str)
Returns: path to a WORKON_HOME directory
Return type: str
- dotfiles.venv.ipython_config.get_pyver(pyverstr=None)[source]¶
Parameters: pyver (str) – “major.minor” e.g. 2.7 or 3.4 (default: sys.version_info[:2]) Returns: python2.7, python.34 Return type: str
- dotfiles.venv.ipython_config.in_ipython_config()[source]¶
Returns: True if get_ipython is in globals() Return type: bool
- dotfiles.venv.ipython_config.ipython_imports()[source]¶
Default imports for IPython (currently unused)
- dotfiles.venv.ipython_config.ipython_main()[source]¶
Function to call if running within IPython, as determined by in_ipython_config .
- dotfiles.venv.ipython_config.logevent(event, obj=None, logger=<logging.Logger object at 0x7fef3c30bf90>, level=10, func=None, lineno=None, modpath=None, show_modpath=None, wrap=False, splitlines=True)[source]¶
Parameters: - event (str) – an event key
- obj (thing) – thing to serialize and log
- logger (logging.Logger) – logger to log to
- level (int) – logging loglevel to log (event, obj)
- wrap (bool) – Add header and footer <event> tags (default: False)
- splitlines (bool) – split by newlines and emit one log message per line
Returns: (event:str, output:str)
Return type: tuple
- dotfiles.venv.ipython_config.lookup_from_kwargs_env(kwargs, env, attr, default=None)[source]¶
__getitem__ from kwargs, env, or default.
Parameters: - kwargs (dict) – kwargs dict
- env (Env) – Env dict
- attr (str) – attribute name
- default (obj) – default value to return if not found in kwargs or env
Returns: kwargs.get(attr, env.get(attr, default))
Return type: obj
- dotfiles.venv.ipython_config.main(*argv, **kwargs)[source]¶
main function called if __name__=="__main__"
Returns: nonzero on error Return type: int
- dotfiles.venv.ipython_config.prepend_comment_char(strblock, commentchar='##')[source]¶
Parameters: - strblock (str) – string to split by newlines and prepend
- prefix (str) – comment string prefix (one space will be added)
Yields: str – lines prefixed with prefix
- dotfiles.venv.ipython_config.shell_quote(var)[source]¶
Escape single quotes and add double quotes around a given variable.
Parameters: _str (str) – string to add quotes to Returns: string wrapped in quotes Return type: str Warning
This is not safe for untrusted input and only valid in this context (os.environ).
dotfiles.venv.ipython_magics module¶
- dotfiles.venv.ipython_magics.magics_class(cls, *args, **kwargs)¶
- dotfiles.venv.ipython_magics.line_magic(func, *args, **kwargs)¶