Environment variables

pshell.source(bash_file, *, stderr=None)

Emulate the bash command source <bash_file>. The stdout of the command, if any, will be redirected to stderr. The acquired variables are injected into os.environment and are exposed to any subprocess invoked afterwards.

Note

The script is always executed with bash. This includes in Windows, where the user needs to make sure bash is installed within %PATH%, and some unixes such as Ubuntu, where /bin/sh is actually dash.

The script is run with errexit, pipefail, nounset.

Parameters:
  • bash_file (str) – Path to the bash file. It can contain environment variables.
  • stderr – standard error file handle. Omit for sys.stderr. Unlike the same parameter for subprocess.call(), which must be backed by a OS-level file descriptor, this can be a pseudo-stream like e.g. io.StringIO.
Raises:

CalledProcessError – if the command returns with non-zero exit status

pshell.putenv(key, value)

Set environment variable. The new variable will be visible to the current process and all subprocesses originating from it.

Unlike os.putenv(), this method resolves environment variables in the value, and it is immediately visible to the current process.

Parameters:
  • key – Variable name
  • value – Variable value. String to set a value, or None to delete the variable. It can be a reference other variables, e.g. ${FOO}.${BAR}.
pshell.override_env(key, value)

Context manager that overrides an environment variable, returns control, and then restores it to its original value.

Parameters:
  • key – Variable name
  • value – Variable value. String to set a value, or None to delete the variable. It can be a reference other variables, e.g. ${FOO}.${BAR}.

Example:

>>> print(os.environ['X'])
foo
>>> with override_env('X', 'bar'):
...     print(os.environ['X'])
bar
>>> print(os.environ['X'])
foo
pshell.resolve_env(s)

Resolve all environment variables in target string.

This command always uses the bash syntax $VARIABLE or ${VARIABLE}. This also applies in Windows. Windows native syntax %VARIABLE% is not supported.

Returns:resolved string
Raises:EnvironmentError – in case of missing environment variable