程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

python多线程与多进程--存活主机ping扫描以及爬取股票价格

发布于2019-08-07 19:33     阅读(626)     评论(0)     点赞(2)     收藏(2)


python多线程与多进程

多线程:

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

普通版本:

 

复制代码
#扫描给定网络中存活的主机(通过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: 线程执行方法接收的参数,该属性是一个元组,如果只有一个参数也需要在末尾加逗号。

多线程版:

复制代码
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:爬取股票的价格

复制代码
多线程
#爬取股票的价格
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)     
复制代码

 

多进程:

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

复制代码
#多进程
#爬取股票的价格
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

复制代码
#爬取股票的价格
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) 
复制代码

 



所属网站分类: 技术文章 > 博客

作者:343ueru

链接:https://www.pythonheidong.com/blog/article/12540/deae439416d009e9276c/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

2 0
收藏该文
已收藏

评论内容:(最多支持255个字符)