服务器之家

服务器之家 > 正文

Python实现多并发访问网站功能示例

时间:2020-11-19 00:26     来源/作者:微烟波

本文实例讲述了Python实现多并发访问网站功能。分享给大家供大家参考,具体如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# Filename:visitweb_threads.py
# Description:python visit web, get startTime, endTime, everytimes spentTime,threading
import threading
import urllib
import time
import datetime
print 'num    web       SpentTime'
def Process(url,n):
  minSpan = 0.0
  maxSpan = 0.0
  sumSpan= 0.0
  over1s = 0
  file = open('data.txt','a') # save Data
  for i in range(n):
    startTime =datetime.datetime.now()
    try:
      urlItem = urllib.urlopen(url)
      htmSource = urlItem.read()
      urlItem.close()
    except:
      pass
    endTime = datetime.datetime.now()
    span = (endTime-startTime).total_seconds()
    sumSpan = sumSpan + span
    if span < minSpan:
      minSpan = span
    if span > maxSpan:
      maxSpan = span
    if span>1:
      over1s=over1s + 1
    print(u'%4d %s Spent:%7s seconds'%(i,url,span))
    file.write(u'%4d %s ST:%s ET:%s Spent :%s seconds\n'%(i,url,startTime,endTime,span))
  file.write('\n')
  print(u'\n requested:%s times\n Total Spent:%s seconds\n avg:%s seconds\n max:%s seconds\n min:%s seconds\n over 1 secnod:%s times\n'%(n,sumSpan,sumSpan/n,maxSpan,minSpan,over1s))
  file.write(u' requested:%s times\n Total Spent:%s seconds\n avg:%s seconds\n max:%s seconds\n min:%s seconds\n over 1 secnod:%s times\n'%(n,sumSpan,sumSpan/n,maxSpan,minSpan,over1s))
  file.close()
class ThreadClass(threading.Thread):
  def run(self):
    now = datetime.datetime.now()
    print "%s says Hello World at time: %s" % (self.getName(), now)
    file = open('threads_data.txt','a') # save threads_data
    file.write( "%s says Hello World at time: %s\n" % (self.getName(), now))
    Process('http://222.20.6.184/main.aspx',10) # visit website 网站的Url和每个进程的访问次数
    now = datetime.datetime.now()
    print "%s says Goodbye at time: %s" % (self.getName(), now)
    file.write( "%s says Goodbye at time: %s\n" % (self.getName(), now))
    file.close()
if __name__=='__main__':
#  file = open('threads_data.txt','w')
#  file.close()
#  file = open('data.txt','w')
#  file.close()
  for i in range(1000): # 多少次同时并发访问
    t = ThreadClass()
    t.start()

希望本文所述对大家Python程序设计有所帮助。

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
电视剧《琉璃》全集在线观看 琉璃美人煞1-59集免费观看地址
电视剧《琉璃》全集在线观看 琉璃美人煞1-59集免费观看地址 2020-08-12
最新idea2020注册码永久激活(激活到2100年)
最新idea2020注册码永久激活(激活到2100年) 2020-07-29
返回顶部