0

我是 python 新手,我正在尝试使用线程池来并行运行这个脚本。但是它不会运行,而只是按顺序运行。脚本基本上遍历 excel 文件以选择设备的 IP 地址,然后根据输入文件发送 xml 请求。我花了几个小时在这上面,我没有得到什么。

def do_upload(xml_file):
for ip in codecIPs:
    try:
        request = open(xml_file, "r").read()
        h = httplib2.Http(".cache")
        h.add_credentials(username, password)
        url = "http://{}/putxml".format(ip)
        print('-'*40)
        print('Uploading Wall Paper to {}'.format(ip))
        resp, content = h.request(url, "POST", body=request,
                              headers={'content-type': 'text/xml; charset=UTF-8'})
        print(content)

    except (socket.timeout, socket.error, httpexception) as e:
            print('failed to connect to {}'.format(codecIPs), e)



pool = ThreadPool(3)
results = pool.map(do_upload('brandinglogo.xml'), codecIPs)
pool.close()
pool.join()
4

1 回答 1

0

由于所谓的全局解释器锁,Python 在其线程模型中没有并行性。基本上,所有线程都只在核心上运行。虽然它启用了并发执行。因此,对于 IO 绑定任务,例如从 Web 下载文件、数据库访问等。您将使用线程来启动这些系统调用,从而获得一些加速。但是对于 CPU 密集型任务,您需要使用 Processes。因此使用多处理 python 库。

于 2019-01-17T09:04:51.383 回答