Redirecting stdin/stdout/setderr and os.execv
Jason Orendorff
jason at jorendorff.com
Wed Jan 16 14:06:08 EST 2002
Richard Philips wrote:
> 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 !
# Use spawnv() instead of fork()/execv().
# This works for me on Windows 2000.
import os, sys
STDIN_FILENO = 0
STDOUT_FILENO = 1
STDERR_FILENO = 2
def run(program, argv, outfile):
orig_stdout = os.dup(STDOUT_FILENO)
try:
new_stdout = os.open(outfile, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
try:
os.dup2(new_stdout, STDOUT_FILENO)
try:
return os.spawnv(os.P_WAIT, program, argv)
finally:
os.dup2(orig_stdout, STDOUT_FILENO)
finally:
os.close(new_stdout)
finally:
os.close(orig_stdout)
status = run("C:\\programs\\cygwin\\bin\\ls.exe",
["ls", "-1"],
"output.txt")
print "ls completed with status:", status
## Jason Orendorff http://www.jorendorff.com/
More information about the Python-list
mailing list