# Path: pyjob/cexec.py
# def cexec(cmd, permit_nonzero=False, **kwargs):
#     """Function to execute a command
# 
#     Parameters
#     ----------
#     cmd : list
#        The command to call
#     permit_nonzero : bool, optional
#        Allow non-zero return codes [default: False]
#     **kwargs : dict, option
#        Any keyword arguments accepted by :obj:`~subprocess.Popen`
# 
#     Returns
#     -------
#     str
#        The processes' standard out
# 
#     Raises
#     ------
#     :exc:`PyJobExecutableNotFoundError`
#        Cannot find executable
#     :exc:`PyJobExecutionError`
#        Execution exited with non-zero return code
# 
#     """
#     executable = which(cmd[0])
#     if executable is None:
#         raise PyJobExecutableNotFoundError(f"Cannot find executable: {cmd[0]}")
#     cmd[0] = executable
# 
#     logger.debug('Executing "%s"', " ".join(cmd))
# 
#     if os.name == "nt":
#         kwargs.setdefault("bufsize", 0)
#         kwargs.setdefault("shell", "False")
# 
#     kwargs.setdefault("cwd", os.getcwd())
#     kwargs.setdefault("stdout", subprocess.PIPE)
#     kwargs.setdefault("stderr", subprocess.STDOUT)
# 
#     stdinstr = kwargs.get("stdin", None)
#     if stdinstr and isinstance(stdinstr, str):
#         kwargs["stdin"] = subprocess.PIPE
# 
#     try:
#         p = subprocess.Popen(cmd, **kwargs)
#         if stdinstr:
#             stdinstr = stdinstr.encode()
#         stdout, stderr = p.communicate(input=stdinstr)
#     except (KeyboardInterrupt, SystemExit):
#         os.kill(p.pid, signal.SIGTERM)
#         sys.exit(signal.SIGTERM)
#     else:
#         if stdout:
#             stdout = decode(stdout).strip()
#         if p.returncode == 0:
#             return stdout
#         elif permit_nonzero:
#             logger.debug(
#                 "Ignoring non-zero returncode %d for '%s'", p.returncode, " ".join(cmd)
#             )
#             return stdout
#         else:
#             raise PyJobExecutionError(
#                 f"Execution of '{' '.join(cmd)}' exited with non-zero return code ({p.returncode})"
#             )
# 
# Path: pyjob/exception.py
# class PyJobExecutableNotFoundError(PyJobError):
#     pass
# 
# class PyJobExecutionError(PyJobError):
#     pass


import os
import sys
import pytest
from pyjob.cexec import cexec
from pyjob.exception import PyJobExecutableNotFoundError, PyJobExecutionError



class TestCexec(object):
    def test_1(self):
        stdout = cexec(
            [sys.executable, "-c", 'import sys; print("hello"); sys.exit(0)']
        )
        assert stdout == "hello"

    def test_2(self):
        with pytest.raises(PyJobExecutionError):
            cexec([sys.executable, "-c", "import sys; sys.exit(1)"])

    def test_3(self):
        cmd = [sys.executable, "-c", 'import sys; print("hello"); sys.exit(1)']
        stdout = cexec(cmd, permit_nonzero=True)
        assert stdout == "hello"

    def test_4(self):
        if sys.version_info < (3, 0):
            cmd = [sys.executable, "-c", "import sys; print(raw_input()); sys.exit(0)"]
        else:
            cmd = [sys.executable, "-c", "import sys; print(input()); sys.exit(0)"]

# Path: pyjob/cexec.py
# def cexec(cmd, permit_nonzero=False, **kwargs):
#     """Function to execute a command
# 
#     Parameters
#     ----------
#     cmd : list
#        The command to call
#     permit_nonzero : bool, optional
#        Allow non-zero return codes [default: False]
#     **kwargs : dict, option
#        Any keyword arguments accepted by :obj:`~subprocess.Popen`
# 
#     Returns
#     -------
#     str
#        The processes' standard out
# 
#     Raises
#     ------
#     :exc:`PyJobExecutableNotFoundError`
#        Cannot find executable
#     :exc:`PyJobExecutionError`
#        Execution exited with non-zero return code
# 
#     """
#     executable = which(cmd[0])
#     if executable is None:
#         raise PyJobExecutableNotFoundError(f"Cannot find executable: {cmd[0]}")
#     cmd[0] = executable
# 
#     logger.debug('Executing "%s"', " ".join(cmd))
# 
#     if os.name == "nt":
#         kwargs.setdefault("bufsize", 0)
#         kwargs.setdefault("shell", "False")
# 
#     kwargs.setdefault("cwd", os.getcwd())
#     kwargs.setdefault("stdout", subprocess.PIPE)
#     kwargs.setdefault("stderr", subprocess.STDOUT)
# 
#     stdinstr = kwargs.get("stdin", None)
#     if stdinstr and isinstance(stdinstr, str):
#         kwargs["stdin"] = subprocess.PIPE
# 
#     try:
#         p = subprocess.Popen(cmd, **kwargs)
#         if stdinstr:
#             stdinstr = stdinstr.encode()
#         stdout, stderr = p.communicate(input=stdinstr)
#     except (KeyboardInterrupt, SystemExit):
#         os.kill(p.pid, signal.SIGTERM)
#         sys.exit(signal.SIGTERM)
#     else:
#         if stdout:
#             stdout = decode(stdout).strip()
#         if p.returncode == 0:
#             return stdout
#         elif permit_nonzero:
#             logger.debug(
#                 "Ignoring non-zero returncode %d for '%s'", p.returncode, " ".join(cmd)
#             )
#             return stdout
#         else:
#             raise PyJobExecutionError(
#                 f"Execution of '{' '.join(cmd)}' exited with non-zero return code ({p.returncode})"
#             )
# 
# Path: pyjob/exception.py
# class PyJobExecutableNotFoundError(PyJobError):
#     pass
# 
# class PyJobExecutionError(PyJobError):
#     pass


# Path: pyjob/tests/test_cexec.py
import os
import sys
import pytest
from pyjob.cexec import cexec
from pyjob.exception import PyJobExecutableNotFoundError, PyJobExecutionError




class TestCexec(object):
    def test_1(self):
        stdout = cexec(
            [sys.executable, "-c", 'import sys; print("hello"); sys.exit(0)']
        )
        assert stdout == "hello"

    def test_2(self):
        with pytest.raises(PyJobExecutionError):
            cexec([sys.executable, "-c", "import sys; sys.exit(1)"])

    def test_3(self):
        cmd = [sys.executable, "-c", 'import sys; print("hello"); sys.exit(1)']
        stdout = cexec(cmd, permit_nonzero=True)
        assert stdout == "hello"

    def test_4(self):
        if sys.version_info < (3, 0):
            cmd = [sys.executable, "-c", "import sys; print(raw_input()); sys.exit(0)"]
        else:
            cmd = [sys.executable, "-c", "import sys; print(input()); sys.exit(0)"]

        stdout = cexec(cmd, stdin="hello")