2013-04-04 13 views
16

Ho questa funzione nel mio programma Python:Python SyntaxError: (" 'ritorno' con l'argomento all'interno del generatore",)

@tornado.gen.engine 
def check_status_changes(netid, sensid):   
    como_url = "".join(['http://131.114.52:44444/ztc?netid=', str(netid), '&sensid=', str(sensid), '&start=-5s&end=-1s']) 

    http_client = AsyncHTTPClient() 
    response = yield tornado.gen.Task(http_client.fetch, como_url) 

    if response.error: 
      self.error("Error while retrieving the status") 
      self.finish() 
      return error 

    for line in response.body.split("\n"): 
       if line != "": 
        #net = int(line.split(" ")[1]) 
        #sens = int(line.split(" ")[2]) 
        #stype = int(line.split(" ")[3]) 
        value = int(line.split(" ")[4]) 
        print value 
        return value 

so che

for line in response.body.split 

è un generatore. Ma vorrei restituire la variabile valore al gestore che ha chiamato la funzione. È possibile? Come posso fare?

+0

'valore di rendimento'. – katrielalex

+0

Già provato ... ma ottengo lo stesso errore ... Penso che sia impossibile inserire un ritorno in un generatore ... – sharkbait

+9

Il ciclo 'for' non è un generatore; l'intera funzione è perché in essa è presente un'istruzione 'yield '. – geoffspear

risposta

23

Non è possibile utilizzare return con un valore per uscire da un generatore. È necessario utilizzare yield più un returnsenza espressione:

if response.error: 
    self.error("Error while retrieving the status") 
    self.finish() 
    yield error 
    return 

Nel ciclo stesso, utilizzare yield ancora:

for line in response.body.split("\n"): 
    if line != "": 
     #net = int(line.split(" ")[1]) 
     #sens = int(line.split(" ")[2]) 
     #stype = int(line.split(" ")[3]) 
     value = int(line.split(" ")[4]) 
     print value 
     yield value 
     return 

Le alternative sono per sollevare un'eccezione o di utilizzare tornado callback, invece.

+0

Ottimo! Ho pensato che l'errore fosse in "valore di ritorno" – sharkbait

Problemi correlati