import os

# Ported from python 2.0 into this code to be able to use it
# and not depend on python 2.0
P_WAIT = 0
P_NOWAIT = P_NOWAITO = 1

def _spawnvef(mode, file, args, env, func):
    # Internal helper; func is the exec*() function to use
    pid = os.fork()
    if not pid:
        # Child
        try:
            if env is None:
                func(file, args)
            else:
                func(file, args, env)
        except:
            os._exit(127)
    else:
        # Parent
        if mode == P_NOWAIT:
            return pid # Caller is responsible for waiting!
        while 1:
            wpid, sts = os.waitpid(pid, 0)
            if os.WIFSTOPPED(sts):
                continue
            elif os.WIFSIGNALED(sts):
                return -WTERMSIG(sts)
            elif os.WIFEXITED(sts):
                return os.WEXITSTATUS(sts)
            else:
                raise error, "Not stopped, signaled or exited???"

def spawnv(mode, file, args):
    """spawnv(mode, file, args) -> integer

Execute file with arguments from args in a subprocess.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it."""
    return _spawnvef(mode, file, args, None, os.execv)

