Help a newbie use Python's OS module:
Donn Cave
donn at u.washington.edu
Fri Oct 6 18:39:40 EDT 2000
Quoth Kevin O'Gorman <kogorman at pacbell.net>:
| I can use os.fork() to create a child process, but I cannot
| get messages from the child to the parent through the pipe
| I've created.
|
| If anyone's got a little sample program that shows how this
| is done, I'd sure appreciate it.
|
| At the moment, my (non-working) version complains that the
| parent's attemts to read the pipe are failing. It looks
| like this:
|
|
| #! /usr/bin/python
| # $Id: fork.py,v 1.2 2000/10/06 04:17:32 kevin Exp kevin $
|
| import string
| import sys
| import re
| import os
|
| print "Running $Id: fork.py,v 1.2 2000/10/06 04:17:32 kevin Exp kevin $"
|
| osi=sys.stdin
| oso=sys.stdout
| ose=sys.stderr
|
| rw=os.pipe()
| r=rw[0]
| w=rw[1]
| print "Reading on",r,", and writing on",w
| child=os.fork()
| if child==0:
| sys.stderr.write("In child\n")
| os.close(1)
| os.dup(w)
| sys.stdout=os.fdopen(1,"w")
| os.close(r)
| os.close(w)
|
| sys.stderr.write("Writing\n")
| print "foo"
| print "bar"
| print "foobuar"
| sys.stdout.close()
| sys.exit(0)
|
| os.close(0)
| os.dup(r)
| sys.stdin=os.fdopen(r) ## <-----
| os.close(r)
| os.close(w)
|
| print "Stdin is ",sys.stdin
| print "about to read"
| lin=sys.stdin.readline()
| if not lin:
| print "Read failed",lin
| sys.exit(1)
| while lin:
| print lin
|
| lin=sys.stdin.readline()
I think you will recognize the nature of the problem right away.
Try sys.stdin = os.fdopen(0), in the parent.
I find dup2() easier to use than dup(). I rarely use file objects
in this kind of thing, because of their buffering. In this example
I don't see any problems with either of those, though.
Donn Cave, donn at u.washington.edu
More information about the Python-list
mailing list