国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

Python實(shí)現(xiàn)可設(shè)置持續(xù)運(yùn)行時(shí)間、線程數(shù)及時(shí)間間隔的多線程異步

2020-02-16 11:35:27
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

本文實(shí)例講述了Python實(shí)現(xiàn)可設(shè)置持續(xù)運(yùn)行時(shí)間、線程數(shù)及時(shí)間間隔的多線程異步post請(qǐng)求功能。分享給大家供大家參考,具體如下:

#coding=utf8'''random.randint(a, b):用于生成一個(gè)指定范圍內(nèi)的整數(shù)。其中參數(shù)a是下限,參數(shù)b是上限,生成的隨機(jī)數(shù)n: a <= n <= brandom.choice(sequence):從序列中獲取一個(gè)隨機(jī)元素參數(shù)sequence表示一個(gè)有序類型(列表,元組,字符串)'''import httplib,jsonimport timeimport threadingfrom random import randint,choice#創(chuàng)建請(qǐng)求函數(shù)def postRequest(threadNum):  postJson={        }  #定義需要進(jìn)行發(fā)送的數(shù)據(jù)  postData=json.dumps(postJson)  #定義一些文件頭  headerdata = {    "content-type":"application/json",     }  #接口  requrl ="/v1/query"  #請(qǐng)求服務(wù),例如:www.baidu.com  hostServer=""  #連接服務(wù)器  conn = httplib.HTTPConnection(hostServer)  #發(fā)送請(qǐng)求  conn.request(method="POST",url=requrl,body=postData,headers=headerdata)  #獲取請(qǐng)求響應(yīng)  response=conn.getresponse()  #打印請(qǐng)求狀態(tài)  if response.status in range(200,300):    print u"線程"+str(threadNum)+u"狀態(tài)碼:"+str(response.status)  conn.close()def run(threadNum,internTime,duration):  #創(chuàng)建數(shù)組存放線程  threads=[]  try:    #創(chuàng)建線程    for i in range(1,threadNum):      #針對(duì)函數(shù)創(chuàng)建線程      t=threading.Thread(target=postRequest,args=(i,))      #把創(chuàng)建的線程加入線程組      threads.append(t)  except Exception,e:    print e  try:    #啟動(dòng)線程    for thread in threads:        thread.setDaemon(True)        thread.start()        time.sleep(internTime)    #等待所有線程結(jié)束    for thread in threads:        thread.join(duration)  except Exception,e:      print eif __name__ == '__main__':  startime=time.strftime("%Y%m%d%H%M%S")  now=time.strftime("%Y%m%d%H%M%S")  duratiion=raw_input(u"輸入持續(xù)運(yùn)行時(shí)間:")  while (startime+str(duratiion))!=now:    run(10,1,int(duratiion))    now=time.strftime("%Y%m%d%H%M%S")

運(yùn)行結(jié)果:

更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python Socket編程技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 浮梁县| 阳曲县| 屏山县| 凯里市| 合阳县| 根河市| 镶黄旗| 秭归县| 布尔津县| 五原县| 鹤岗市| 东阳市| 嘉定区| 会宁县| 玉龙| 华亭县| 弥勒县| 偏关县| 南漳县| 榕江县| 胶南市| 迁安市| 东至县| 额尔古纳市| 武冈市| 宝山区| 霍邱县| 长治县| 怀来县| 大丰市| 黄大仙区| 南投县| 康马县| 马边| 永胜县| 宁城县| 日喀则市| 蓬安县| 九寨沟县| 芦溪县| 密云县|