Concurrent.futures - 返回未定义导入模块的错误

时间:2015-06-25 21:43:27

标签: python python-2.7 concurrent.futures

我正在使用concurrent.futures来多线程处理我正在编写的应用程序。

我通过从netaddr导入IPAddress启动应用程序:

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]

然后我等待结果完成并将它们附加到输出var:

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

我遇到的问题是我将来会继续获得优势:

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由于错误而停止执行脚本时,我可以清楚地看到IPAddress是在内存中定义的:

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

1 个答案:

答案 0 :(得分:1)

好的问题是我从main中导入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"

我把它移到了脚本的顶部,一切正常。我很好奇为什么这个有用,如果有人能回答的话。