Source code for conda_subprocess.interface

import os
from subprocess import PIPE, CalledProcessError, CompletedProcess, TimeoutExpired

from conda_subprocess.process import Popen

# use presence of msvcrt to detect Windows-like platforms (see bpo-8110)
_mswindows = os.name == "nt"


# Copied from subprocess.py
[docs] def call(*popenargs, timeout=None, **kwargs): """Run command with arguments. Wait for command to complete or timeout, then return the returncode attribute. The arguments are the same as for the Popen constructor, including the additional `prefix_name`/`prefix_path` keyword arguments used to select the target conda environment (see :func:`conda_subprocess.process.Popen`). Example: retcode = call(["ls", "-l"], prefix_name="py312") """ with Popen(*popenargs, **kwargs) as p: try: return p.wait(timeout=timeout) except: # Including KeyboardInterrupt, wait handled that. p.kill() # We don't call p.wait() again as p.__exit__ does that for us. raise
[docs] def check_call(*popenargs, **kwargs): """Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. The arguments are the same as for the call function, including the additional `prefix_name`/`prefix_path` keyword arguments used to select the target conda environment. Example: check_call(["ls", "-l"], prefix_name="py312") """ retcode = call(*popenargs, **kwargs) if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] raise CalledProcessError(retcode, cmd) return 0
[docs] def check_output(*popenargs, timeout=None, **kwargs): r"""Run command with arguments and return its output. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute. The arguments are the same as for the Popen constructor, including the additional `prefix_name`/`prefix_path` keyword arguments used to select the target conda environment (see :func:`conda_subprocess.process.Popen`). Example: >>> check_output(["ls", "-l", "/dev/null"]) b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' The stdout argument is not allowed as it is used internally. To capture standard error in the result, use stderr=STDOUT. >>> check_output(["/bin/sh", "-c", ... "ls -l non_existent_file ; exit 0"], ... stderr=STDOUT) b'ls: non_existent_file: No such file or directory\n' There is an additional optional argument, "input", allowing you to pass a string to the subprocess's stdin. If you use this argument you may not also use the Popen constructor's "stdin" argument, as it too will be used internally. Example: >>> check_output(["sed", "-e", "s/foo/bar/"], ... input=b"when in the course of fooman events\n") b'when in the course of barman events\n' By default, all communication is in bytes, and therefore any "input" should be bytes, and the return value will be bytes. If in text mode, any "input" should be a string, and the return value will be a string decoded according to locale encoding, or by "encoding" if set. Text mode is triggered by setting any of text, encoding, errors or universal_newlines. """ for kw in ("stdout", "check"): if kw in kwargs: raise ValueError(f"{kw} argument not allowed, it will be overridden.") if "input" in kwargs and kwargs["input"] is None: # Explicitly passing input=None was previously equivalent to passing an # empty string. That is maintained here for backwards compatibility. if ( kwargs.get("universal_newlines") or kwargs.get("text") or kwargs.get("encoding") or kwargs.get("errors") ): empty = "" else: empty = b"" kwargs["input"] = empty return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, **kwargs).stdout
[docs] def run( *popenargs, input=None, capture_output=False, timeout=None, check=False, **kwargs ): """Run command with arguments and return a CompletedProcess instance. The returned instance will have attributes args, returncode, stdout and stderr. By default, stdout and stderr are not captured, and those attributes will be None. Pass stdout=PIPE and/or stderr=PIPE in order to capture them, or pass capture_output=True to capture both. If check is True and the exit code was non-zero, it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute, and output & stderr attributes if those streams were captured. If timeout is given, and the process takes too long, a TimeoutExpired exception will be raised. There is an optional argument "input", allowing you to pass bytes or a string to the subprocess's stdin. If you use this argument you may not also use the Popen constructor's "stdin" argument, as it will be used internally. By default, all communication is in bytes, and therefore any "input" should be bytes, and the stdout and stderr will be bytes. If in text mode, any "input" should be a string, and stdout and stderr will be strings decoded according to locale encoding, or by "encoding" if set. Text mode is triggered by setting any of text, encoding, errors or universal_newlines. The other arguments are the same as for the Popen constructor, including the additional `prefix_name`/`prefix_path` keyword arguments used to select the target conda environment (see :func:`conda_subprocess.process.Popen`). """ if input is not None: if kwargs.get("stdin") is not None: raise ValueError("stdin and input arguments may not both be used.") kwargs["stdin"] = PIPE if capture_output: if kwargs.get("stdout") is not None or kwargs.get("stderr") is not None: raise ValueError( "stdout and stderr arguments may not be used with capture_output." ) kwargs["stdout"] = PIPE kwargs["stderr"] = PIPE with Popen(*popenargs, **kwargs) as process: try: stdout, stderr = process.communicate(input, timeout=timeout) except TimeoutExpired as exc: process.kill() if _mswindows: # Windows accumulates the output in a single blocking # read() call run on child threads, with the timeout # being done in a join() on those threads. communicate() # _after_ kill() is required to collect that and add it # to the exception. exc.stdout, exc.stderr = process.communicate() else: # POSIX _communicate already populated the output so # far into the TimeoutExpired exception. process.wait() raise except: # Including KeyboardInterrupt, communicate handled that. process.kill() # We don't call process.wait() as .__exit__ does that for us. raise retcode = process.poll() if check and retcode: raise CalledProcessError( retcode, process.args, output=stdout, stderr=stderr ) return CompletedProcess(process.args, retcode, stdout, stderr)