2014-10-06 99 views
1

编写一个程序,验证电子邮件语法和MX记录的列表,阻止编程费时,我想这样做异步或线程,这是我的代码:扭曲执行的同时,10个线程,并等待结果

with open(file_path) as f: 
    # check the status of file, if away then file pointer will be at the last index 
    if (importState.status == ImportStateFile.STATUS_AWAY): 
     f.seek(importState.fileIndex, 0) 

    while True: 
     # the number of emails to process is configurable 10 or 20 
     emails = list(islice(f, app.config['NUMBER_EMAILS_TO_PROCESS'])) 
     if len(emails) == 0: 
      break; 

     importState.fileIndex = importState.fileIndex + len(''.join(emails)) 

     for email in emails: 
      email = email.strip('''<>;,'\r\n ''').lower() 
      d = threads.deferToThread(check_email, email) 
      d.addCallback(save_email_status, email, importState) 

     # set the number of emails processed 
     yield set_nbrs_emails_process(importState) 

     # do an insert of all emails 
     yield reactor.callFromThread(db.session.commit) 

# set file status as success 
yield finalize_import_file_state(importState) 
reactor.callFromThread(reactor.stop) 

检查电子邮件功能:

def check_email(email): 
    pipe = subprocess.Popen(["./check_email", '--email=%s' % email], stdout=subprocess.PIPE) 
    status = pipe.stdout.read() 
    try: 
     status = int(status) 
    except ValueError: 
     status = -1 

    return status 

什么,我需要的是过程,同时10封电子邮件,并等待结果。

+0

有10封电子邮件,还是您想同时发送不超过10封电子邮件? – jfs 2014-10-10 00:00:22

+0

你的代码中是否有'@ inlineCallBacks'装饰器(隐含所有'yield'语句)? – jfs 2014-10-10 00:02:28

+0

是的,有@ @ inlineCallBacks',我想通过批量处理10或20封电子邮件,然后将它插入到数据库中。 – 2014-10-10 07:24:55

回答

2

我不确定为什么在您的示例代码中涉及到线程。您不需要线程与Twisted进行电子邮件交互,也不需要同时这样做。

如果你有一个返回Deferred异步函数,你可以把它叫做十次工作的十个不同的流将同时进行:

for i in range(10): 
    async_check_email_returning_deferred() 

如果你想知道的所有十个结果时可用,您可以使用gatherResults:

from twisted.internet.defer import gatherResults 
... 
email_results = [] 
for i in range(10): 
    email_results.append(async_check_mail_returning_deferred()) 
all_results = gatherResults(email_results) 

all_results是一个Deferred将火的时候,在所有的email_resultsDeferreds已经解雇(或当他们第一次的科幻res与Failure)。

+0

你可以把这个函数的代码'async_check_email_returning_deferred' – 2014-10-06 12:55:00

+0

它是任何函数返回一个Deferred。我不确定“检查电子邮件”是什么意思,所以我不知道如何实现这个功能。它可能会使用'twisted.mail'中的一些API。 – 2014-10-07 01:05:53

+0

我已经添加了检查功能 – 2014-10-09 22:14:27