Python 高度定制化自己的线程类和进程类代码,获取启动进程或线程方法的结果(兼容Py2和Py3)

时间:2022-02-27 06:59:21
#encoding=utf-8
from threading import Thread
from multiprocessing import Process
import multiprocessing
'''
Author liuyancong
''' class My_Job_With_Thread(Thread):
def run(self):
t_flag = True
b = None
try:
b = self._Thread__target(*self._Thread__args, **self._Thread__kwargs)
except AttributeError as e:
b = self._target(*self._args, **self._kwargs)
t_flag = False
finally:
if t_flag:
del self._Thread__target;del self._Thread__args;del self._Thread__kwargs
else:
del self._target, self._args, self._kwargs
# TODO 你可以在这做你想做的事情
print(b) class My_Job_With_Process(Process):
def run(self):
res = None
if self._target:
res = self._target(*self._args, **self._kwargs)
print (res)
#TODO 你可以在这做你想做的事情 def k(b):
print('K方法开始执行')
return b if __name__ == '__main__':
My_Job_With_Process(target=k, args=('lyc_Process',)).start()
My_Job_With_Thread(target=k,args=('lyc_Thread',)).start()
print('end')

1 、我们重写线程和进程类的run方法,首先是加上它们原来的代码,然后再执行自己的逻辑,保证自己传入的函数正常运行。

因为py2 和py3的线程run方法不同所以这里做了异常捕获来对完成代码。

py27下  Thread的run 方法如下(使用了类的私有属性 __属性名):所以我们通过   self._类名__属性名  来获取如

def run(self):
"""Method representing the thread's activity. You may override this method in a subclass. The standard run() method
invokes the callable object passed to the object's constructor as the
target argument, if any, with sequential and keyword arguments taken
from the args and kwargs arguments, respectively. """
try:
if self.__target: #在子类中使用 self._Thread__target来获取
self.__target(*self.__args, **self.__kwargs) finally: # Avoid a refcycle if the thread is running a function with # an argument that has a member that points to the thread. del self.__target, self.__args, self.__kwargs

而在py3中 Thread的run 方法如下:

2 、因为Process类在Windows平台下只能运行在  

if __name__ == '__main__': 下面
所以我们在这里使用了这个,Thread就没有这个限制,其实可以在这样写
My_Job_With_Thread(target=k,args=('lyc_Thread',)).start()
if __name__ == '__main__':
My_Job_With_Process(target=k, args=('lyc_Process',)).start()
print('end')

3、经过这样重写继承,我们就可以在自己启动的进程或者线程中去处理自己传入的函数的结果,这样可以满足一些比较奇葩的需求。