0
点赞
收藏
分享

微信扫一扫

python中在类的成员函数中启动子进程,子进程为另一个成员函数


1、一般情况下可以在main函数中将类的成员函数当做子进程来进行调用,代码如下:

import time
import threading



# *****************************************************************
# Thread function Example
# *****************************************************************
class ThreadExample:

def LinTable(self):
while(True):
print "I am thread function"
time.sleep(1)


if __name__ == '__main__':
example = ThreadExample()
print "I am main function"
time.sleep(2)
t1 = threading.Thread(target=example.LinTable)
t1.setDaemon(True)
t1.start()

运行程序,结果如下:

python中在类的成员函数中启动子进程,子进程为另一个成员函数_子进程

python中在类的成员函数中启动子进程,子进程为另一个成员函数_main函数_02

点击shell的restart,可以终止程序运行

python中在类的成员函数中启动子进程,子进程为另一个成员函数_成员函数_03

2、有时候需要将python文件做成接口,此时是不带main函数的,想要将成员函数当做子进程来运行,需要

在另一个成员函数中调用该成员函数,调用过程和在main函数中调用类似,代码如下:

import time
import threading



# *****************************************************************
# Thread function Example
# *****************************************************************
class ThreadExample:

def LinTable(self):
while(True):
print "I am thread function"
time.sleep(1)

def LinScheduleTable(self):
print "I am thread schedule function"
time.sleep(2)
t1 = threading.Thread(target=self.LinTable)
t1.setDaemon(True)
t1.start()
return


if __name__ == '__main__':
example = ThreadExample()
example.LinScheduleTable()

运行结果和步骤一中一样:

python中在类的成员函数中启动子进程,子进程为另一个成员函数_子进程_04

在将python程序当做接口文件时,将main函数去掉即可

 

举报

相关推荐

0 条评论