spawnv( ) or spawnl( ) do not launch a normal running process in Python 2.2.2?

Jeff Epler jepler at unpythonic.net
Tue Aug 5 22:43:52 CEST 2003


the third argument to os.spawnv is an argument list as in execv, not a
command string as in popen and system.  The statement you listed
    > os.spawnv(os.P_NOWAIT,'/usr/bin/python',('python hello.py >/dev/null
runs the Python binary with its argv[0] set to 'python hello.py >/dev/null',
which is probably going to drop into trying to read a script from
standard input since there is no script or command on the commandline,
but I'm not really sure what to expect in this crazy case.

There's no easy way to do command redirections while using spawnv.
Here's a piece of code to do so with fork+exec [tested]:
    def F(x):
        if not isinstance(x, int): return x.fileno()

    def coroutine(args, child_stdin, child_stdout, child_stderr):
        pid = os.fork()
        if pid == 0:
            os.dup2(F(child_stdin), 0)
            os.dup2(F(child_stdout), 1)
            os.dup2(F(child_stderr), 2)
            os.execvp(args[0], args)
        return pid
you could do something similar with os.spawnv [untested]:
    def dup2_noerror(a, b):
        try:
            os.dup2(a, b)
        except:
            pass

    def coroutine_spawnv(flags, args, child_stdin, child_stdout, child_stderr):
        old_stdin = os.dup(0)
        old_stdout = os.dup(1)
        old_stderr = os.dup(2)
        try:
            os.dup2(F(child_stdin), 0)
            os.dup2(F(child_stdout), 1)
            os.dup2(F(child_stderr), 2)
            return os.spawnv(flags, args[0], args)
        finally:
            dup2_noerror(old_stdin, 0)
            dup2_noerror(old_stdout, 1)
            dup2_noerror(old_stderr, 2)

Jeff





More information about the Python-list mailing list