python day Twelve

简介:

python day Twelve

一、线程池(补充)

1.上下文管理  

2.终止线程池操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
1. 线程和队列
 
import  queue
import  threading
 
class  ThreadPool( object ):
     def  __init__( self , max_num = 20 ):          #max_num:固定队列参数20
         self .queue  =  queue.Queue(max_num)
         for  in  range (max_num):             #往队列里边循环加线程
             self .queue.put(threading.Thread)
     def  get_thread( self ):                    #获取线程
         return  self .queue.get()
     def  add_thread( self ):                    #增加线程,用于不断增加线程
         self .queue.put(threading.Thread)
 
pool  =  ThreadPool( 10 )            #定义线程池10个
def  func(arg, p):
     print  (arg)
     import  time
     time.sleep( 2 )                #等待2s
     p.add_thread()               #上边执行完一个任务后,线程自动关闭,再手动增加一个线程到队列。
 
for  in  range ( 30 ):              #有30个任务需要执行
     thread  =  pool.get_thread()    #从队列里获取一个线程
     =  thread(target = func, args = (i, pool))
     t.start()                    #启动线程
     
     
2. 上下文管理和终止线程操作
 
import  queue
import  threading
import  contextlib
import  time
 
StopEvent  =  object ()
class  ThreadPool( object ):
     def  __init__( self , max_num, max_task_num  =  None ):
         if  max_task_num:
             self .q  =  queue.Queue(max_task_num)
         else :
             self .q  =  queue.Queue()
         self .max_num  =  max_num
         self .cancel  =  False
         self .terminal  =  False
         self .generate_list  =  []
         self .free_list  =  []
     def  run( self , func, args, callback = None ):
         """
         线程池执行一个任务
         :param func: 任务函数
         :param args: 任务函数所需参数
         :param callback: 任务执行失败或成功后执行的回调函数,回调函数有两个参数1、任务函数执行状态;2、任务函数返回值(默认为None,即:不执行回调函数)
         :return: 如果线程池已经终止,则返回True否则None
         """
         if  self .cancel:
             return
         if  len ( self .free_list)  = =  0  and  len ( self .generate_list) <  self .max_num:
             self .generate_thread()
         =  (func, args, callback,)
         self .q.put(w)
 
     def  generate_thread( self ):                       #创建一个线程
         =  threading.Thread(target = self .call)
         t.start()
 
     def  call( self ):                          #循环去获取任务函数并执行任务函数
         current_thread  =  threading.currentThread()
         self .generate_list.append(current_thread)
         event  =  self .q.get()
         while  event ! =  StopEvent:
             func, arguments, callback  =  event
             try :
                 result  =  func( * arguments)
                 success  =  True
             except  Exception as e:
                 success  =  False
                 result  =  None
             if  callback  is  not  None :
                 try :
                     callback(success, result)
                 except  Exception as e:
                     pass
             with  self .worker_state( self .free_list, current_thread):
                 #上下文管理,内部运行一个装饰器,具体内容看例3
                 if  self .terminal:
                     event  =  StopEvent
                 else :
                     event  =  self .q.get()
         else :
             self .generate_list.remove(current_thread)
 
     def  close( self ):                         #执行完所有的任务后,所有线程停止
         self .cancel  =  True
         full_size  =  len ( self .generate_list)
         while  full_size:
             self .q.put(StopEvent)
             full_size  - =  1
     def  terminate( self ):                     #无论是否还有任务,终止线程
         self .terminal  =  True
         while  self .generate_list:
             self .q.put(StopEvent)
         self .q.queue.clear()
     @contextlib.contextmanager
     def  worker_state( self , state_list, worker_thread):
         #用于记录线程中正在等待的线程数
         state_list.append(worker_thread)
         try :
             yield
         finally :
             state_list.remove(worker_thread)
# How to use
pool  =  ThreadPool( 5 )
def  callback(status, result):
     # status, execute action status
     # result, execute action return value
     pass
def  action(i):
     print (i)
for  in  range ( 30 ):
     ret  =  pool.run(action, (i,), callback)
 
time.sleep( 5 )
print ( len (pool.generate_list),  len (pool.free_list))
print ( len (pool.generate_list),  len (pool.free_list))
# pool.close()            #等待任务结束之后,终止线程;终止线程池操作方法1.
pool.terminate()           #无论是否还有任务,终止线程;终止线程池操作方法2.
 
python  3.0 官方上下文管理详见:https: / / docs.python.org / 3 / library / contextlib.html


二、redis 发布订阅


三、rabbitMQ



四、mysql


五、python pymysql模块


六、python ORM框架:SQLAchemy


七、python Paramiko模块


八、基于Paramiko模块来看堡垒机如何实现





     本文转自506554897 51CTO博客,原文链接:http://blog.51cto.com/506554897/1846557,如需转载请自行联系原作者



相关文章
|
12天前
|
安全 Java 数据处理
Python网络编程基础(Socket编程)多线程/多进程服务器编程
【4月更文挑战第11天】在网络编程中,随着客户端数量的增加,服务器的处理能力成为了一个重要的考量因素。为了处理多个客户端的并发请求,我们通常需要采用多线程或多进程的方式。在本章中,我们将探讨多线程/多进程服务器编程的概念,并通过一个多线程服务器的示例来演示其实现。
|
12天前
|
程序员 开发者 Python
Python网络编程基础(Socket编程) 错误处理和异常处理的最佳实践
【4月更文挑战第11天】在网络编程中,错误处理和异常管理不仅是为了程序的健壮性,也是为了提供清晰的用户反馈以及优雅的故障恢复。在前面的章节中,我们讨论了如何使用`try-except`语句来处理网络错误。现在,我们将深入探讨错误处理和异常处理的最佳实践。
|
16天前
|
缓存 监控 Python
解密Python中的装饰器:优雅而强大的编程利器
Python中的装饰器是一种强大而又优雅的编程工具,它能够在不改变原有代码结构的情况下,为函数或类添加新的功能和行为。本文将深入解析Python装饰器的原理、用法和实际应用,帮助读者更好地理解和利用这一技术,提升代码的可维护性和可扩展性。
|
1月前
|
编译器 测试技术 C++
【Python 基础教程 01 全面介绍】 Python编程基础全攻略:一文掌握Python语法精髓,从C/C++ 角度学习Python的差异
【Python 基础教程 01 全面介绍】 Python编程基础全攻略:一文掌握Python语法精髓,从C/C++ 角度学习Python的差异
164 0
|
4天前
|
安全 数据处理 开发者
《Python 简易速速上手小册》第7章:高级 Python 编程(2024 最新版)
《Python 简易速速上手小册》第7章:高级 Python 编程(2024 最新版)
17 1
|
4天前
|
人工智能 数据挖掘 程序员
《Python 简易速速上手小册》第1章:Python 编程入门(2024 最新版)
《Python 简易速速上手小册》第1章:Python 编程入门(2024 最新版)
34 0
|
5天前
|
API Python
Python模块化编程:面试题深度解析
【4月更文挑战第14天】了解Python模块化编程对于构建大型项目至关重要,它涉及代码组织、复用和维护。本文深入探讨了模块、包、导入机制、命名空间和作用域等基础概念,并列举了面试中常见的模块导入混乱、不适当星号导入等问题,强调了避免循环依赖、合理使用`__init__.py`以及理解模块作用域的重要性。掌握这些知识将有助于在面试中自信应对模块化编程的相关挑战。
18 0
|
6天前
|
Python
Python金融应用编程:衍生品定价和套期保值的随机过程
Python金融应用编程:衍生品定价和套期保值的随机过程
|
7天前
|
Python
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
44 0
|
7天前
|
机器学习/深度学习 算法 定位技术
python中使用马尔可夫决策过程(MDP)动态编程来解决最短路径强化学习问题
python中使用马尔可夫决策过程(MDP)动态编程来解决最短路径强化学习问题
22 1