Selenium with Python學(xué)習(xí)點(diǎn)滴
作者:
-voyage- 發(fā)布時(shí)間:
[ 2016/7/19 14:27:55 ] 推薦標(biāo)簽:
功能測試 單元測試 線程
從結(jié)果可以看出,一次執(zhí)行5個(gè)py文件,必須等5個(gè)全部執(zhí)行完畢之后才繼續(xù)執(zhí)行,如果有一個(gè)文件耗時(shí)比較長的話整個(gè)過程卡住了.
所以需要用隊(duì)列來解決該問題.
1 #! /usr/bin/env python
2 #coding=utf-8
3 import threading
4 from multiprocessing import Queue
5 from time import ctime,sleep
6 from subprocess import Popen,PIPE
7 lock=threading.Lock()
8 class MyThread(threading.Thread):
9 def __init__(self,queue):
10 threading.Thread.__init__(self)
11 self.queue=queue
12 def run(self):
13 while True:
14 if not self.queue.empty():
15 filename=self.queue.get()
16 p=Popen("python "+filename,shell=True,stdout=PIPE)
17 #由于此處非線程安全,打印結(jié)果會(huì)有點(diǎn)亂
18 #如果用鎖會(huì)導(dǎo)致線程等待,影響效率,此處只是示例
19 print p.stdout.readlines()
20 else:
21 print 'end'
22 break
23 if __name__=='__main__':
24 print 'main start time:%s' %ctime()
25 file=[]
26 for j in range(50):
27 file.append("E:\python\sub.py")
28 finishjob = 0
29 queue = Queue()
30 for filename in file:
31 queue.put(filename)
32 my_threads=[]
33 for x in range(5):
34 my_thread=MyThread(queue)
35 #設(shè)置守護(hù)線程,主線程退出后其它線程也會(huì)退出
36 my_thread.daemon=True
37 my_threads.append(my_thread)
38 my_thread.start()
39 for t in my_threads:
40 t.join()
41 print 'main end time:%s' %ctime()
main start time:Wed Jun 22 09:59:11 2016
[[[['Start:59:11
'['Start:59:11
''Start:59:11
''Start:59:11
', 'Star
t:59:11
', 'sleep:10
''sleep:6
', 'slee, 's, 'End:59:21
']
leep:25
'p:27
', 'End:59:38
']
, 'End:59:17
']
, , 'sl'End:59:36
'eep:29
', ]'End:59:40
']
['Start:59:41
', 'sleep:18
', 'End:59:59
']
['Start:59:59
', 'sleep:11
', 'End:00:10
']
.....