Help a newbie use Python's OS module:
Kevin O'Gorman
kogorman at pacbell.net
Wed Oct 11 16:38:41 EDT 2000
Donn Cave wrote:
>
> 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
Right on, of course. Thanks for the help. Everything will be
so much easier now that I have a working example.
I must admit, though, that I didn't quite understand the comment
about no using file objects. Doesn't it get cumbersome to
direct output to the raw descriptors? What do you use?
I didn't see anything like fprintf, or a way to set sys.stdout
to a descriptor (a bare int doesn't work).
++ kevin
--
Kevin O'Gorman (805) 650-6274 mailto:kogorman at pacbell.net
Permanent e-mail forwarder: mailto:Kevin.O'Gorman.64 at Alum.Dartmouth.org
At school: mailto:kogorman at cs.ucsb.edu
Web: http://www.cs.ucsb.edu/~kogorman/index.html
Web: http://trixie.kosman.via.ayuda.com/~kevin/index.html
More information about the Python-list
mailing list