‘壹’ 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并在将其传递给下一个线程之前执行一些操作,也就产生了并行执行的错觉。