使用守护进程线程的Python多线程处理

2024-10-03 17:16:40 发布

您现在位置:Python中文网/ 问答频道 /正文

出于个人目的,我试图建立一个不同工具的框架。在

为此,我需要将主线程创建为守护线程。这个守护进程线程在命令行中通过输入framework(其别名为python 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线程:

^{pr2}$

Tags: 工具selfnone进程defgui线程daemon