Python Concurrent.futures-返回未定义导入模块的错误
我正在使用concurrent.futures对我正在编写的应用程序进行多线程处理 我通过从NetAddress导入IPAddress启动应用程序:Python Concurrent.futures-返回未定义导入模块的错误,python,python-2.7,concurrent.futures,Python,Python 2.7,Concurrent.futures,我正在使用concurrent.futures对我正在编写的应用程序进行多线程处理 我通过从NetAddress导入IPAddress启动应用程序: from netaddr import IPNetwork, IPAddress 接下来,我获取一些输入文件,并将它们全部传递到多线程函数中: with open(options.filename) as f: contents = f.readlines() executor = concurrent.futures.Proce
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]
然后,我等待获得已完成的结果并将其附加到输出变量:
for future in concurrent.futures.as_completed(futures):
output.append(future.results()
我所面临的问题是,我一直在从未来获得超额:
global name 'IPAddress' is not defined
以下是ip_比较功能:
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"
你知道为什么futures无法识别加载的模块吗
当我的IDE由于错误而停止执行脚本时,我可以清楚地看到内存中定义了IPAddress:
IPAddress = {type} <class 'netaddr.ip.IPAddress'>
IPAddress={type}
好的,问题是我从main中导入NetAddress:
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"
我把这个移到了剧本的顶端,一切都很顺利。不过,如果有人能回答的话,我很好奇这为什么会起作用。Per,“工作子进程必须导入\uuuu main\uuu
模块。这意味着ProcessPoolExecutor不会在交互式解释器中工作。”这意味着每个工作子进程都导入\uu main\uu
模块。因此,如果uuu name uuu=='\uuuuuu main uuu'得到定义,则外部的全局变量将被定义。if语句
中的语句不会执行。