简体   繁体   中英

How to return value and don't break loop

I want to create tool, which will parse and return messages from my email. You can see part of my code below. This is very simpliest part, in reality code much bigger. I have at least 2 iterations on 'for' loop and I want to return each result of operation, but return breaks the loop. I can add results to list, but I need just string, not list. The best way for me it's return result and continue loop, but this is impossible. Maybe I need to define new function or use lambda function for it and get result recursively? I didn't works with recursion before. Also I know that this is possible to use 'yield', but how to returns values from generator then?

def a(request_url):
output = getImap(request_url)

def getImap(request_url):
    #many code before.....
    mail = imaplib.IMAP4_SSL(output['hostname'], port=output['port'])
    typ, data = mail.fetch(output['parameter']['uid'], 'RFC822')
    msg = email.message_from_string(data[0][1])
    for part in msg.walk():
        res = part.get_payload(decode=True)
        return res

def AcceptDef(res):
    print res

Hopefully I understood enough of the question and this can help you. There are two ways to go about what you're trying to do, depending on what your end design is.

Either you call the function you want for each item (within your loop):

for part in msg.walk():
    res = part.get_payload(decode=True)
    AcceptDef(res)

Or you can yield instead of return creating a generator over which you can iterate.

def walker(amount):  # stands in for getting wanted items.
    for item in range(amount):
        yield item

def printer(text):   # stands in for your action
    print(text)

for i in walker(5):  # iterate over all items ...
    printer(i)       # ... calling a corresponding action

EDIT: as tobias_k pointed out in the comment. If you need to perform different action on different iterations, but still prefer to do so from within the loop, you could of course pass this in as an argument and perform accordingly. An example:

def rinseandrepeat(amount, fce):
    for item in range(amount):
        fce(item)

def printer1(text):
    print('P1:', text)

def printer2(text):
    print('P2:', text)

rinseandrepeat(2, printer1)  # calls printer1() for each item
rinseandrepeat(2, printer2)  # calls printer2() for each item

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM