【发布时间】:2014-10-06 09:48:01
【问题描述】:
编写一个程序来验证电子邮件语法列表和 MX 记录,因为阻塞编程很耗时,我想异步或通过线程执行此操作,这是我的代码:
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 封电子邮件并等待结果。
【问题讨论】:
-
是否有 10 封电子邮件,或者您希望同时发送不超过 10 封电子邮件?
-
您的代码中是否有
@inlineCallBacks装饰器(由所有yield语句暗示)? -
是的,有
@inlineCallBacks,我想批量处理10或20封邮件,然后插入DB。 -
如果您不关心限制并发处理的电子邮件数量,那么只需按照@Jean-Paul Calderone 的建议使用
gatherResults()。 -
您可能应该打开一个单独的问题,关于如何发送一封电子邮件而不会阻止扭曲。
标签: python multithreading python-2.7 twisted