[英]Improving speed of python script
无论如何,有没有提高以下速度。 该代码在http请求中插入修饰符。 修改者是5位数字的电子邮件ID。 目标是将每个结果附加到JSON文件中。
我知道摆脱Progessbar()会有所帮助,但我发现减慢速度值得使用该函数。 “尝试除其他以外”部分再次降低了速度,但退出时很多,但是idents有4500个条目。 有任何想法吗?
import urllib3
import json
import csv
from progressbar import ProgressBar
pbar = ProgressBar()
with open('blim2.csv', newline='') as csvfile:
idents = csv.reader(csvfile, delimiter=' ', quotechar='|')
json_arr = []
while True:
try:
for x in pbar(idents):
http = urllib3.PoolManager()
r = http.request('GET', 'https://api.pipedrive.com/v1/mailbox/mailMessages/'+"".join(x)+'?include_body=1&api_token=token')
mails = json.loads(r.data.decode('utf-8'))
json_arr.append(mails)
with open('test2.json', 'w') as outfile:
json.dump(json_arr, outfile)
except:
continue
else:
break
尝试将while True
循环一直移动到内部,以仅重试单个请求。 另外,最后只写入一次文件。
import urllib3
import json
import csv
from progressbar import ProgressBar
import time
pbar = ProgressBar()
base_url = 'https://api.pipedrive.com/v1/mailbox/mailMessages/'
fields = {"include_body": "1", "api_token": "token"}
json_arr = []
http = urllib3.PoolManager()
with open('blim2.csv', newline='') as csvfile:
for x in pbar(csv.reader(csvfile, delimiter=' ', quotechar='|')):
while True:
try:
r = http.request('GET', base_url + "".join(x), fields=fields)
break
except Exception:
# wait a bit before trying again
time.sleep(1) # seconds
mails = json.loads(r.data.decode('utf-8'))
json_arr.append(mails)
with open('test2.json', 'w') as outfile:
json.dump(json_arr, outfile)
你也应该看看起来实际上是在你的情况而被提出什么异常except
只。 否则,您可能会掩盖其他问题。 我已经用except Exception
except
替换了您的裸机,这至少允许用户按Ctrl + C终止程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.