2014-10-06 105 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