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)

python多线程与多进程--存活主机ping扫描以及爬取股票价格的更多相关文章

  1. Python多线程和多进程谁更快?

    python多进程和多线程谁更快 python3.6 threading和multiprocessing 四核+三星250G-850-SSD 自从用多进程和多线程进行编程,一致没搞懂到底谁更快.网上很 ...

  2. python多线程与多进程及其区别

    个人一直觉得对学习任何知识而言,概念是相当重要的.掌握了概念和原理,细节可以留给实践去推敲.掌握的关键在于理解,通过具体的实例和实际操作来感性的体会概念和原理可以起到很好的效果.本文通过一些具体的例子 ...

  3. Python 多线程、多进程 (三)之 线程进程对比、多进程

    Python 多线程.多进程 (一)之 源码执行流程.GIL Python 多线程.多进程 (二)之 多线程.同步.通信 Python 多线程.多进程 (三)之 线程进程对比.多线程 一.多线程与多进 ...

  4. Python 多线程、多进程 (一)之 源码执行流程、GIL

    Python 多线程.多进程 (一)之 源码执行流程.GIL Python 多线程.多进程 (二)之 多线程.同步.通信 Python 多线程.多进程 (三)之 线程进程对比.多线程 一.python ...

  5. Python 多线程、多进程 (二)之 多线程、同步、通信

    Python 多线程.多进程 (一)之 源码执行流程.GIL Python 多线程.多进程 (二)之 多线程.同步.通信 Python 多线程.多进程 (三)之 线程进程对比.多线程 一.python ...

  6. 基于Windows平台的Python多线程及多进程学习小结

    python多线程及多进程对于不同平台有不同的工具(platform-specific tools),如os.fork仅在Unix上可用,而windows不可用,该文仅针对windows平台可用的工具 ...

  7. 使用 Python 查看局域网内存活主机

    1 安装 (如果误用了 pip insatll nmap的话,要先 pip uninstall nmap) pip install python-nmap Nmap 是一款用于网络发现和安全审计的网络 ...

  8. python 多线程、多进程

    一.首先说下多线程.多进程用途及异同点,另外还涉及到队列的,memcache.redis的操作等: 1.在python中,如果一个程序是IO密集的操作,使用多线程:运算密集的操作使用多进程. 但是,其 ...

  9. python多线程,多进程

    线程是公用内存,进程内存相互独立 python多线程只能是一个cpu,java可以将多个线程平均分配到其他cpu上 以核为单位,所以GIL(全局锁,保证线程安全,数据被安全读取)最小只能控制一个核,很 ...

随机推荐

  1. Perl输出复杂数据结构:Data::Dumper,Data::Dump,Data::Printer

    输出复杂结构 Data::Dumper.Data::Dump.Data::Printer都可以用来输出复杂的数据结构.本文只介绍简单的几个输出形式,以后再需要的地方再详细介绍. 前两者建议传递数据结构 ...

  2. 关于Newtonsoft.Json,LINQ to JSON的一个小demo

    nuget获取Newtonsoft.Json github地址:Newtonsoft.Json public static void Test1() { /* 文本格式如下 代码实现目的: 1.VR ...

  3. wpf学习20180606

    对象元素的子元素 有三类子元素:内容属性.集合项.值(类型转换) ------------------------------------------------------------------- ...

  4. asp.net-常用服务器控件-20180329

    常用服务器控件 1.文本类型控件 Label控件 TextBox控件 2.按钮类型控件 Button控件 ImageButton控件 3.选择类型控件 CheckBox控件 RadioButton控件 ...

  5. [android] 隐式意图和显式意图的使用场景

    激活系统的某些应用,并且往应用里面填一些数据,比如说短信应用 打开短信应用,查看logcat,找到ActivityManager, 看到Display.com.android.mms/.ui.Comp ...

  6. laravel5.5 Syntax error or access violation: 1071 Specified key was too long

    在laravel5.5执行数据迁移时 php artisan migrate 先说下系统环境: ubutun Ubuntu 16.04.3 LTS mysql:5.6.35-log 经查自Larave ...

  7. 【Linux】linux查看日志文件内容命令tail、cat、tac、head、echo

    linux查看日志文件内容命令tail.cat.tac.head.echo tail -f test.log你会看到屏幕不断有内容被打印出来. 这时候中断第一个进程Ctrl-C, ---------- ...

  8. Idea 15 激活

    https://www.cnblogs.com/moko/p/5012006.html 1.把补丁下载到自己的电脑上 2.打开idea,help->edit custom VM options ...

  9. 开源前端脚本错误监控及跟踪解决项目-BadJS 试用

    BadJS 是 一个web 前端脚本错误监控及跟踪项目.此项目为鹅厂 imweb(qq群:179045421) 团队的开源项目.此项目支持单机,集群,docker.存储支持mongodb等. 官网文档 ...

  10. Ansible playbook roles

    1  概述 角色(roles):如果我们使用playbook写成一个文件,这个文件会很大,但是不方便组织,我们可以分组,把playbook根据功能,如handler,tasks等分门别类的放在在各自的 ...