前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python多线程与多进程--存活主机p

python多线程与多进程--存活主机p

作者头像
py3study
发布2020-01-17 16:56:39
5360
发布2020-01-17 16:56:39
举报
文章被收录于专栏:python3python3

python多线程与多进程

多线程:

案例:扫描给定网络中存活的主机(通过ping来测试,有响应则说明主机存活)

普通版本:

代码语言:javascript
复制
#扫描给定网络中存活的主机(通过ping来测试,有响应则说明主机存活)
import sys
import subprocess
import time
def ping(net,start=100,end=200,n=2,w=5):
    for i in range(start,end+1):
        ip=net+"."+str(i)
        command="ping %s -n %d -w %d"%(ip,n,w)
        print(ip,("通","不通")[subprocess.call(command,stdout=open("nul","w"))]) #stdout=open("nul","w") #不显示命令执行返回的结果
t1=time.time()
if len(sys.argv)!=2:
    print("参数输入错误!")
    print("运行示例:")
    print("test01.py 123.125.114")
elif len(sys.argv)==2:
    net=sys.argv[1]
    ping(net)
t2=time.time()
print("程序耗时%f秒!"%(t2-t1))   #195.091611秒

运行效果如下:

在python里面,线程的创建有两种方式,其一使用Thread类创建 导入Python标准库中的Thread模块 from threading import Thread  创建一个线程 mthread = threading.Thread(target=function_name, args=(function_parameter1, function_parameterN))  启动刚刚创建的线程 mthread .start() function_name: 需要线程去执行的方法名 args: 线程执行方法接收的参数,该属性是一个元组,如果只有一个参数也需要在末尾加逗号。

多线程版:

代码语言:javascript
复制
import sys
import subprocess
import time
from threading import Thread
#在python里面,线程的创建有两种方式,其一使用Thread类创建
# 导入Python标准库中的Thread模块 
#from threading import Thread #
# 创建一个线程 
#mthread = threading.Thread(target=function_name, args=(function_parameter1, function_parameterN)) 
# 启动刚刚创建的线程 
#mthread .start()
#function_name: 需要线程去执行的方法名
#args: 线程执行方法接收的参数,该属性是一个元组,如果只有一个参数也需要在末尾加逗号。

result=[]
def ping1(ip):
    command="ping %s -n 1 -w 20"%(ip)
    result.append([ip,subprocess.call(command)])
def ping(net,start=100,end=200):
    for i in range(start,end+1):
        ip=net+"."+str(i)
        th=Thread(target=ping1,args=(ip,))
        th.start()
    
def main():
    if len(sys.argv)!=2:
        print("参数输入错误!")
        print("运行示例:")
        print("test01.py 123.125.114")
    elif len(sys.argv)==2:
        net=sys.argv[1]
        ping(net)
if __name__=='__main__':
    t1=time.time()
    main()
    while len(result)!=101:
        time.sleep(1)
print(result)        
t2=time.time()
print("程序耗时%f秒!"%(t2-t1))   #1.585263秒

多线程案例2:爬取股票的价格

代码语言:javascript
复制
多线程
#爬取股票的价格
import requests
import re
import time
from threading import Thread

code=[600016,600000,601939,600036,603683,600050,601890,600795,601857,600584,601231,603165,600644,603005,601198,603690,600643,600131,600776,603609,601377]
m1=re.compile(r"price: '(\d{1,3}\.\d{2}')")
def getprice(id):
    url="http://quotes.money.163.com/0%s.html"%id
    txt=requests.get(url).text
    price=m1.search(txt).group(1)
    print(id,price)

if __name__=="__main__":
    ts=[]
    start=time.time()
    for id in code:
        t=Thread(target=getprice,args=(id,))
        ts.append(t)
        t.start()
    for t in ts:
        t.join()    #等待子线程运行完,主线程再运行
    print("程序耗时:",time.time()-start)     

多进程:

爬取股票的价格(多进程版)

代码语言:javascript
复制
#多进程
#爬取股票的价格
import requests
import re
import time
from multiprocessing import Process
from threading import Thread 
code=[600016,600000,601939,600036,603683,600050,601890,600795,601857,600584,601231,603165,600644,603005,601198,603690,600643,600131,600776,603609,601377]
m1=re.compile(r"price: '(\d{1,3}\.\d{2}')") 
def getprice(id):
    url="http://quotes.money.163.com/0%s.html"%id
    txt=requests.get(url).text
    price=m1.search(txt).group(1)
    print(id,price)
ps=[]   #进程池    
if __name__=="__main__":
    start=time.time()
    for id in code:
        p=Process(target=getprice,args=(id,))
        ps.append(p) #把进程放入列表(进程池)
        p.start()   #启动进程
    for p in ps:
        p.join()
    print(time.time()-start)  

爬取股票的价格(多进程版)带Pool

代码语言:javascript
复制
#爬取股票的价格
import requests
import re
import time
from multiprocessing import Pool
#多进程带Pool
 
code=[600016,600000,601939,600036,603683,600050,601890,600795,601857,600584,601231,603165,600644,603005,601198,603690,600643,600131,600776,603609,601377]
m1=re.compile(r"price: '(\d{1,3}\.\d{2}')")     
def getprice(id):
    url="http://quotes.money.163.com/0%s.html"%id
    txt=requests.get(url).text
    price=m1.search(txt).group(1)
    print(id,price)

if __name__=="__main__":
    start=time.time()
    p=Pool(4)
    for id in code:
        p.apply_async(getprice,args=(id,))  #async异步,第一个参数是函数名,第二个是此函数的参数
    p.close()   
    p.join()    #等待子线程运行完,主线程再运行
    print("程序耗时:",time.time()-start) 
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-05-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档