Redirecting stdin/stdout/setderr and os.execv

Richard Philips Richard.Philips at ua.ac.be
Wed Jan 16 12:40:23 EST 2002


Jason Orendorff wrote:

>>How do I redirect stdin, stdout en stderr from within a python script 
>>together with os.execv:
>>
>
>import os
>

>
># POSIX constants
>STDIN_FILENO = 0
>STDOUT_FILENO = 1
>STDERR_FILENO = 2
>
>out_fd = os.open("/tmp/output", os.O_WRONLY | os.O_CREAT)
>os.dup2(out_fd, STDOUT_FILENO)
>os.execv("/bin/ls", ["ls", "-ls"])
>
>>I am looking for a replacement for os.system which is
>>independent of the pecularities of the shell in use.
>>
>
>You may find that you want to fork() before doing
>execv(), then, as execv() replaces your Python process
>and does not return!
>
>Using os.fork(), os.dup2(), and os.exec*(), plus os.pipe(),
>you can write non-shell versions of os.popen() and the
>popen2 functions.
>
>You can also write
>  f = open("/tmp/output", "w")
>  out_fd = f.fileno()
>to get the file descriptor.
>
>Consider getting a book by W. Richard Stevens.
>
>## Jason Orendorff    http://www.jorendorff.com/
>

I understand the solution, and it solves the problem on UNIX.

But os.fork() is not usable on win32.



I would like a solution which work both on UNIX and windows !


Thank you,


Richard Philips
University of Antwerp







More information about the Python-list mailing list