有没有可能的方法来加速我的代码使用多处理接口?问题是这个接口使用map函数,它只对1个函数起作用。但我的代码有三个功能。我试着把我的职能结合起来,但没有成功。我的脚本从文件中读取站点的URL并对其执行3个函数。For循环使它非常慢,因为我有很多url
import requests
def Login(url): #Log in
payload = {
'UserName_Text' : 'user',
'UserPW_Password' : 'pass',
'submit_ButtonOK' : 'return buttonClick;'
}
try:
p = session.post(url+'/login.jsp', data = payload, timeout=10)
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout):
print "site is DOWN! :", url[8:]
session.cookies.clear()
session.close()
else:
print 'OK: ', p.url
def Timer(url): #Measure request time
try:
timer = requests.get(url+'/login.jsp').elapsed.total_seconds()
except (requests.exceptions.ConnectionError):
print 'Request time: None'
print '-----------------------------------------------------------------'
else:
print 'Request time:', round(timer, 2), 'sec'
def Logout(url): # Log out
try:
logout = requests.get(url+'/logout.jsp', params={'submit_ButtonOK' : 'true'}, cookies = session.cookies)
except(requests.exceptions.ConnectionError):
pass
else:
print 'Logout '#, logout.url
print '-----------------------------------------------------------------'
session.cookies.clear()
session.close()
for line in open('text.txt').read().splitlines():
session = requests.session()
Login(line)
Timer(line)
Logout(line)
是的,您可以使用多处理。
请求
session
不能是全局的,并且不能在工作进程之间共享,每个工作进程都应该使用自己的会话。你写道,你已经“试图把我的职能结合在一起,但没有成功”。到底什么不起作用?
有很多方法可以完成你的任务,但是在这个层次上不需要多处理,它只会增加复杂性,imho。
看看gevent,greenlets和monkey patching吧!
代码准备好后,可以将主函数包装到gevent循环中,如果应用了monkey补丁,gevent框架将同时运行N个作业(可以创建作业池、设置并发限制等)
这个例子应该有助于:
您可以在here和Github repository中找到更多信息,本例来自
附则。 greenlet也可以处理请求,您不需要更改代码。
相关问题 更多 >
编程相关推荐