『壹』 python循環怎麼用多線程去運行
背景:Python腳本:讀取文件中每行,放入列表中;循環讀取列表中的每個元素,並做處理操作。
核心:多線程處理單個for循環函數調用
模塊:threading
第一部分:
:多線程腳本 (該腳本只有兩個線程,t1循環次數<t2)#!/usr/bin/env python#-*- coding: utf8 -*- import sysimport timeimport stringimport threadingimport datetimefileinfo = sys.argv[1] # 讀取文件內容放入列表host_list = []port_list = [] # 定義函數:讀取文件內容放入列表中def CreateList(): f = file(fileinfo,'r') for line in f.readlines(): host_list.append(line.split(' ')[0]) port_list.append(line.split(' ')[1]) return host_list return port_list f.close() # 單線程 循環函數,注釋掉了#def CreateInfo(): # for i in range(0,len(host_list)): # 單線程:直接循環列表# time.sleep(1)# TimeMark = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')# print "The Server's HostName is %-15s and Port is %-4d !!! [%s]" % (host_list[i],int(port_list[i]),TimeMark)# # 定義多線程循環調用函數def MainRange(start,stop): #提供列表index起始位置參數 for i in range(start,stop): time.sleep(1) TimeMark = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') print "The Server's HostName is %-15s and Port is %-4d !!! [%s]" % (host_list[i],int(port_list[i]),TimeMark) # 執行函數,生成列表CreateList()# 列表分割成:兩部分 mid為列表的index中間位置mid = int(len(host_list)/2) # 多線程部分threads = []t1 = threading.Thread(target=MainRange,args=(0,mid))threads.append(t1)t2 = threading.Thread(target=MainRange,args=(mid,len(host_list)))threads.append(t2) for t in threads: t.setDaemon(True) t.start()t.join()print "ok"
以上是腳本內容!!!
----------------------------------------------------------------------
:讀取文件的內容
文件內容:
[root@monitor2 logdb]# cat hostinfo.txt
192.168.10.11 1011
192.168.10.12 1012
192.168.10.13 1013
192.168.10.14 1014
192.168.10.15 1015
192.168.10.16 1016
192.168.10.17 1017
192.168.10.18 1018
192.168.10.19 1019
192.168.10.20 1020
192.168.10.21 1021
192.168.10.22 1022
192.168.10.23 1023
192.168.10.24 1024
192.168.10.25 1025
:輸出結果:
單線程 : 執行腳本:輸出結果:
[root@monitor2 logdb]# ./Threadfor.py hostinfo.txt
The Server's HostName is 192.168.10.10 and Port is 1010 !!! [2017-01-10 14:25:14]
The Server's HostName is 192.168.10.11 and Port is 1011 !!! [2017-01-10 14:25:15]
The Server's HostName is 192.168.10.12 and Port is 1012 !!! [2017-01-10 14:25:16]
.
.
.
The Server's HostName is 192.168.10.25 and Port is 1025 !!! [2017-01-10 14:25:29]
多線程:執行腳本:輸出 結果
[root@monitor2 logdb]# ./Threadfor.py hostinfo.txt
The Server's HostName is 192.168.10.11 and Port is 1011 !!! [2017-01-10 14:51:51]
The Server's HostName is 192.168.10.18 and Port is 1018 !!! [2017-01-10 14:51:51]
The Server's HostName is 192.168.10.12 and Port is 1012 !!! [2017-01-10 14:51:52]
The Server's HostName is 192.168.10.19 and Port is 1019 !!! [2017-01-10 14:51:52]
The Server's HostName is 192.168.10.13 and Port is 1013 !!! [2017-01-10 14:51:53]
The Server's HostName is 192.168.10.20 and Port is 1020 !!! [2017-01-10 14:51:53]
The Server's HostName is 192.168.10.14 and Port is 1014 !!! [2017-01-10 14:51:54]
The Server's HostName is 192.168.10.21 and Port is 1021 !!! [2017-01-10 14:51:54]
The Server's HostName is 192.168.10.15 and Port is 1015 !!! [2017-01-10 14:51:55]
The Server's HostName is 192.168.10.22 and Port is 1022 !!! [2017-01-10 14:51:55]
The Server's HostName is 192.168.10.16 and Port is 1016 !!! [2017-01-10 14:51:56]
The Server's HostName is 192.168.10.23 and Port is 1023 !!! [2017-01-10 14:51:56]
The Server's HostName is 192.168.10.17 and Port is 1017 !!! [2017-01-10 14:51:57]
The Server's HostName is 192.168.10.24 and Port is 1024 !!! [2017-01-10 14:51:57]
The Server's HostName is 192.168.10.25 and Port is 1025 !!! [2017-01-10 14:51:58]
『貳』 python 多線程爬取網站數據利用線程池
"""
@author: wangxingchun
多線程(線程池)
下載數據
"""
import requests
import csv
from concurrent.futures import ThreadPoolExecutor as tp
#創建一個csv文件,注意創建writer對象"csv.writer()"
f = open('xinfadi.csv','w',encoding='utf8')
csvwrite = csv.writer(f)
#如果寫入txt文件,不需要創建writer對象。
# f = open('xinfadidata.txt','w',encoding='utf8')
#創建一個函數,以頁碼做為參數
def down(n_page):
url = 'http://www.xinfadi.com.cn/getPriceData.html'
data = {'count': 428225,'current': n_page,'limit': 20}
resp = requests.post(url,data=data)
datas =resp.json()
#通過分析數據嵌套情況,獲取數據。此處可在網頁開發工具json數據中查看分析。
for i in range(len(datas['list'])):
name = datas['list'][i]['prodName']
highPrice = datas['list'][i]['highPrice']
lowPrice = datas['list'][i]['lowPrice']
pubDate = datas['list'][i]['pubDate']
place = datas['list'][i]['place']
csvwrite.writerow((name,highPrice,lowPrice,pubDate,place))#writerow要求寫入的是可迭代對象
# f.writelines(f'{name},{highPrice},{lowPrice},{pubDate},{place} ')
resp.close()
if __name__ == '__main__':
with tp(50) as t: #創建線程池,
for n in range(1,101): #遍歷數據網頁
t.submit(down,n) #提交給線程池,進行多線程下載
print(f'共{n}頁數據下載完畢!')
f.close()
『叄』 關於python多線程問題求解
看下面的代碼 你就理解了,至於業務邏輯自己去實現
#coding:utf-8
importthreading
if__name__=="__main__":
obj={'test':'關於python多線程問題求解'}
t=threading.Thread(target=Run_One,args=(obj,))
t.setDaemon(False)
t.start()
defRun_One(objvalue):
ls_threadone=[]#線程集合
foriinrange(1,8):
t=threading.Thread(target=Run_Two,args=(i,objvalue))
t.setDaemon(False)
t.start()
ls_threadone.append(t)
fortinls_threadone:
t.join()#等待所有線程執行完畢如果禁用那麼直接向下執行
print("線程全部執行完畢")defRun_Two(types,dataList):
print("多個參數傳遞")
『肆』 python py文件同時開兩個線程可以嗎
可以的。
Python 多線程
多線程類似於同時執行多個不同程序,多線程運行有如下優點:
使用線程可以把占據長時間的程序中的任務放到後台去處理。
用戶界面可以更加吸引人,這樣比如用戶點擊了一個按鈕去觸發某些事件的處理,可以彈出一個進度條來顯示處理的進度
程序的運行速度可能加快
在一些等待的任務實現上如用戶輸入、文件讀寫和網路收發數據等,線程就比較有用了。在這種情況下我們可以釋放一些珍貴的資源如內存佔用等等。
線程在執行過程中與進程還是有區別的。每個獨立的進程有一個程序運行的入口、順序執行序列和程序的出口。但是線程不能夠獨立執行,必須依存在應用程序中,由應用程序提供多個線程執行控制。
每個線程都有他自己的一組CPU寄存器,稱為線程的上下文,該上下文反映了線程上次運行該線程的CPU寄存器的狀態。
指令指針和堆棧指針寄存器是線程上下文中兩個最重要的寄存器,線程總是在進程得到上下文中運行的,這些地址都用於標志擁有線程的進程地址空間中的內存。
線程可以被搶占(中斷)。
在其他線程正在運行時,線程可以暫時擱置(也稱為睡眠) -- 這就是線程的退讓。
『伍』 python讀取大文件處理時使用多線程
如果有個很大的文件,幾十G?,需要每次讀取一部分,處理後再讀取剩餘部分。
with open as f 已經從內部處理難點,使用 for line in f 以迭代器的形式每次讀取一行,不會有內存問題。
下面程序的思路是用一個列表存放讀取到的數據,達到長度後就開始處理,處理完就清空列表,繼續執行
『陸』 python 多進程讀取同一個循環處理、可以用multiprocessing
可以每個在func中加上一個參數data,data是這個線程處理的數據;
多線程處理的時候,給每個線程分配相應的data就可以了。
給個示例:
#-*-coding:utf-8-*-
importthread,threading
importtime
defFuncTest(tdata):
printtdata
classmythread(threading.Thread):
def__init__(self,threadname):
threading.Thread.__init__(self)
defrun(self):
lock.acquire()
FuncTest(ft)
lock.release()
defMutiThread(num):
threads=[]
i=0
globalft
forxinxrange(num):
threads.append(mythread(num))
fortinthreads:
time.sleep(0.5)
lock.acquire()
ft=GetThreadParam(datafile,num,i)
#print'[%s]Thread:%s,Testdata:%s'%(time.ctime(),t,ft)
i=i+1
t.start()
lock.release()
fortinthreads:
t.join()
defGetThreadParam(datafile,num,curthread):
#線程數需要小於文件行數
f=open(datafile,'r')
lines=f.readlines()
divres=divmod(len(lines),num)
ifcurthread<(num-1):
res=lines[curthread*divres[0]:(curthread+1)*divres[0]]
elifcurthread==(num-1):
res=lines[curthread*divres[0]:((curthread+1)*divres[0]+divres[1])]
returnres
f.close()
if__name__=='__main__':
globalnum,lock
datafile='a.txt'
num=3#num並發數
lock=threading.Lock()
MutiThread(num)
a.txt文件內容如下
1
2
3
4
5
6
7
8
9
10
3個線程並發時,運行結果:
>>>
['1 ', '2 ', '3 ']
['4 ', '5 ', '6 ']
['7 ', '8 ', '9 ', '10']
『柒』 python udp多線程的問題
for out_port in self.output_port:
soc = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
soc.connect(("localhost",out_port))
_output.append(soc)
不要用output_port,用input_port。
你這里是往input_port發送數據,不需要關心自己的port,而是對端的port
『捌』 python 怎麼實現多線程的
線程也就是輕量級的進程,多線程允許一次執行多個線程,Python是多線程語言,它有一個多線程包,GIL也就是全局解釋器鎖,以確保一次執行單個線程,一個線程保存GIL並在將其傳遞給下一個線程之前執行一些操作,也就產生了並行執行的錯覺。