August 4th, 2003, 05:42 AM
Returning a value without breaking from function?
I'm trying to solve a bit of a conundrum here. I have a function (well, to be precise a class method) that opens a pipe and uses a while loop to go through the output line by line. It needs to return some information from each line as it comes, and previously I've achieved that by having a function called "printProgress" that is called in the while loop and that, well, prints the progress!
The problem is that for various reasons this isn't satisfactory any more. I need to be able to do something like:
The problem of course is that "return" will break from the function on the first call.
(open the pipe, etc.)
(do something here)
I've read a little about yield, and think it might be what I'm looking for, but I can't figure out how to use it. I've also considered opening a fifo, but that seems a little extreme.
August 4th, 2003, 07:14 AM
From the looks of this page it seems yield does what you want. There's a few examples/explanations on it's usage which might help.
August 4th, 2003, 08:24 AM
Yeah, yield is looking pretty good. What we need added is a return that keeps going without exiting. Yield would be nicer still if it returned a readable value instead of a <generator.. but it works, you just need to call list or tuple on the function (you can't make a string or dictionary this way which sucks, infact i can't).
Can't see me ever using it unless i have too i really don't like how it works..
August 4th, 2003, 08:41 AM
I can't get how it works at the moment; every time I experiment I get an error. I'm going to have to find some examples, since the python docs only seem to mention it in the "language lawyers" section.
August 4th, 2003, 10:54 AM
Aha! I correct myself... here's a working example:
That function lets me safely handle running external commands and parse the output line by line (in conjuction with another function to kill the pipe, kill_pipe()).
# This is needed in Python < 2.3
from __future__ import generators
import os, popen2
def run(self, program, arguments):
"""Runs a program; supply program name (string) and arguments (list)"""
command = arguments
command[:0] = [program]
self.pipe = popen2.Popen4(command)
pid = self.pipe.pid
line = self.pipe.fromchild.read(1000)
if not line:
# Clean up process table
for line in run('runme', ['real', 'quick']):