让我们说我有以下代码(start.py
)启动一个帖子并且永不退出(注意:不要介意拼写错误或缺少某些代码行,只需明白这个想法。):
from threading import Thread
from anApp import AnApp
class ClassA(Thread):
def __init__(self, _parent):
Thread.__init__(self)
self.parent = _parent
def run(self):
while 1:
self.parent.anApp.execute()
# Here, I want to known if the thread started in appX.py is alive.
# if the thread stated by appX.py is alive:
# print 'App x is running'
# else:
# print 'App x is not running'
class App():
def __init__(self):
self.th = None
self.anApp = AnApp()
def someFunction(self):
self.th = ClassA(self)
self.th.start()
现在,anApp.py
看起来像这样:
from appX import App
Class AnApp():
# def __init__(self) goes here...
def execute(self):
self.appX = App()
self.appX.startRunning()
最后,appX.py
看起来像这样(类似于start.py
):
from threading import Thread
class ClassX(Thread):
def __init__(self, _parent):
Thread.__init__(self)
self.parent = _parent
def run(self):
while 1:
print 'Im here!!!'
class App():
# def __init__(self) goes here....
def startRunning(self):
self.listen = ClassX(self)
self.listen.start()
我想知道startRunning
中appX.py
启动的帖子是否还活着,start.py
(请查看我上面写的评论)。
答案 0 :(得分:0)
看起来你想要这个,虽然你的示例代码在某些方面似乎不一致,所以我不能100%肯定这将适用于你的真实代码:
def run(self):
while 1:
self.parent.anApp.execute() # Do you really want this inside the infinite loop?
if self.parent.anApp.appX.listen.is_alive():
print 'App x is running'
else:
print 'App x is not running'
这假设appX.py
看起来像这样:
from threading import Thread
class ClassX(Thread):
def __init__(self, _parent):
Thread.__init__(self)
self.parent = _parent
def run(self):
while 1:
print 'Im here!!!'
class App():
# def __init__(self) goes here....
def startRunning(self):
self.listen = ClassX(self)
self.listen.start()