2015-06-25 71 views
1

我正在使用concurrent.futures多線程編寫我正在編寫的應用程序。Concurrent.futures - 返回導入模塊未定義的錯誤

from netaddr import IPNetwork, IPAddress 

接下來,我需要一些輸入文件,我通過他們的進入我的功能被多線程:

with open(options.filename) as f: 
    contents = f.readlines() 
    executor = concurrent.futures.ProcessPoolExecutor(threads) 
    futures = [executor.submit(ip_compare, ip, scope_list) for ip in contents] 

那我等得到

我從netaddr中輸入ip地址啓動應用程序結果完成並將它們追加到輸出變量:

for future in concurrent.futures.as_completed(futures): 
    output.append(future.results() 

我遇到的問題是t帽子我不斷收到來自未來EXCETION:

global name 'IPAddress' is not defined 

這裏是ip_compare功能:

def ip_compare(ip_addr, scope_list): 
    ip_addr = ip_addr.rstrip() 
    if not is_ipv4(ip_addr): 
     try: 
      ip = socket.gethostbyname(ip_addr) 
     except: 
      return "error," + ip_addr + ",,," + str(sys.exc_info()[0]).replace(',',';') + "\r\n" 
    else: 
     ip = ip_addr 
    for scope in scope_list: 
     if IPAddress(ip) in IPNetwork(scope): 
      return "in," + ip_addr + "," + ip + "," + scope + ",\r\n" 
    return "out," + ip_addr + "," + ip + "," + ",,\r\n" 

任何想法,爲什麼期貨不能識別加載模塊?

當我的IDE停止腳本的執行,因爲錯誤的,我可以清楚地看到,ip地址是在內存中定義:

IPAddress = {type} <class 'netaddr.ip.IPAddress'> 

回答

1

確定這樣的問題是,我是從內主要進口netaddr中:

if __name__=="__main__": 
try: 
    from netaddr import IPNetwork, IPAddress 
except ImportError as error: 
    print "Please install netaddr.\r\npip install netaddr\r\n\r\nIf pip is not installed, install pip\r\nhttps://pip.pypa.io/en/latest/installing.html" 

我把它移到腳本的頂部,一切正常。我很好奇,爲什麼這個工作雖然,如果任何人都可以回答。

+0

Per [the docs](https://docs.python.org/3/library/concurrent.futures.html#processpoolexecutor),*「__main__'模塊必須可由工作程序子進程導入,這意味着ProcessPoolExecutor在交互式解釋器中不起作用。「*這意味着每個工作者子過程輸入'__main__'模塊。因此'if __name__ =='__main __''之外的全局變量被定義。 'if語句'中的那些不會被執行。 – unutbu