Environment variables

pshell.source(bash_file: str | Path, *, stderr: IO | None = None) 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

This function is not available on Windows.

The script is always executed with bash. This includes when running in Ubuntu and derivatives, where /bin/sh is actually dash.

The script is run with errexit, pipefail, nounset.

Parameters:
  • bash_file – 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: str, value: str | Path | None) None

Set environment variable. The new variable will be visible to the current process and all subprocesses forked 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}. Path objects are transparently converted to strings.

pshell.override_env(key: str, value: str | Path | None) Iterator[None]

Context manager that overrides an environment variable, returns control, and then restores it to its original value (or deletes it if it did not exist before).

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}. Path objects are transparently converted to strings.

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: str) str
pshell.resolve_env(s: Path) Path

Resolve all environment variables in target string or Path.

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

Unlike in os.path.expandvars(), undefined variables raise an exception instead of being silently replaced by an empty string.

Parameters:

s – string or Path potentially containing environment variables

Returns:

resolved string, or Path if the input is a Path

Raises:

EnvironmentError – in case of missing environment variable