Redirecting stdin/stdout/setderr and os.execv

Jason Orendorff jason at jorendorff.com
Wed Jan 16 11:14:19 EST 2002


> 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/




More information about the Python-list mailing list