带有守护程序线程的Python多线程

时间:2018-04-12 09:20:04

标签: python multithreading daemon

出于个人目的,我正在尝试设置不同工具的框架。

为此,我需要将主线程创建为守护线程。通过键入frameworkpython framework.py的别名),可以在命令行中启动此守护程序线程。

该线程应该创建一个子线程,这是一个GUI界面(类似于metasploit)。在该GUI界面中,您可以使用use <module>命令在模块中导航,然后使用run在后​​台运行它。您要运行的每个模块都是由主守护程序线程创建的守护程序线程。

因此,这些工具在后台运行,需要一些时间(天)。这就是为什么你可以离开GUI界面,主守护程序线程仍在处理用于运行工具的子守护程序线程。

我尝试过类似的东西,但是应该启动GUI界面的子线程(由主守护程序线程创建)不会使用 stdout 来打印东西,因此我没有图形界面。如果没有使用任何库(TKinter,QThread,......),你知道是否有任何方法可以很容易地修复它?

整理

我有一个主守护程序线程处理图形界面的线程和后台运行工具的守护程序线程。它还处理工具的图形界面和守护程序线程之间的通信(例如,用户可以使用kill命令,以便主守护程序线程杀死子守护程序线程以获取工具。)

结束总结

这是我的主题模块:

class IOThread(threading.Thread):
    def __init__(self, inQueue, outQueue, fct, fctParam=None, daemon=True):
        threading.Thread.__init__(self)
        self.inQueue = inQueue
        self.outQueue = outQueue
        self.fct = fct
        self.fctParam = fctParam
        # Set properties and start thread
        self.daemon = daemon
        self.start()

    def run(self):

        while True:

            #Get from queue job
            inObj = self.inQueue.get()
            if self.fctParam is None:
                outObj = self.fct (inObj)
            else:
                outObj = self.fct (inObj, self.fctParam)

            if self.outQueue is not None:
                self.outQueue.put(outObj)

            self.inQueue.task_done()

# To be used to launch the GUI from the main daemon thread
def launchGUI(function):
    try:
        inQueue = Queue()
        inQueue.put(None)

        IOThread(inQueue, None, function, daemon=False)

    except TypeError as e: print(e)

这就是我启动应该创建和启动GUI线程的主守护程序线程的方法:

# create the graphic interface
def openGUI():
    # prints some stuffs for the graphic interface

# create the graphic thread
def mainloop():
    try: launchGUI(openGUI)
    except Exception as e: print(e)

# starts in daemon and launch the graphic thread
if __name__ == "__main__":
    with daemon.DaemonContext():
        mainloop()

0 个答案:

没有答案