在Python中同时使用多线程和多处理的Python(需要帮助)
我有一个GUI,当您单击submit按钮时,它会创建一个多线程(因此GUI不会冻结),它调用一个多进程函数,通过我创建的这个线程调用一个辅助函数 我对使用多处理/线程还不熟悉,需要一些帮助才能使其按我所需的方式运行 当前,当我运行下面的代码时,它不会执行函数中的代码:apply\u async\u with\u callback。它只打印该函数中的语句。在apply_async_with_callback中,如果我删除args=(a_device,vpnternation),并将这两个参数放入我调用的第二个函数“start_commands”(start_commands(a_device,vpnternation)),它将启动所有函数中的代码,但在执行3个进程时,一次只执行一个操作 长话短说,我在GUI中创建了一个线程,让它调用apply\u async函数,该函数执行另一个函数(start\u命令)的多处理。我不确定我是否遗漏了一些关于线程或处理如何操作的信息(我假设是这样,因为它没有正确执行) 注意:没有线程,如果我只是让多处理在GUI冻结时执行,它就会工作 任何帮助都将不胜感激,谢谢在Python中同时使用多线程和多处理的Python(需要帮助),python,multithreading,python-multiprocessing,Python,Multithreading,Python Multiprocessing,我有一个GUI,当您单击submit按钮时,它会创建一个多线程(因此GUI不会冻结),它调用一个多进程函数,通过我创建的这个线程调用一个辅助函数 我对使用多处理/线程还不熟悉,需要一些帮助才能使其按我所需的方式运行 当前,当我运行下面的代码时,它不会执行函数中的代码:apply\u async\u with\u callback。它只打印该函数中的语句。在apply_async_with_callback中,如果我删除args=(a_device,vpnternation),并将这两个参数放入我
class OutputWindowGUI(object):
def __init__(self, root):
self.root = root
#Removed the GUI code that isn't needed, to shorten the amount of code shown.
self.gui_thread = threading.Thread(target = self.apply_async_with_callback)
self.gui_thread.start()
def start_commands(self, a_device, vpntermination):
try:
self.net_connect = ConnectHandler(**a_device)
self.hostname = self.net_connect.send_command("show hostname") #Used to store Hostname.
self.output = self.net_connect.send_command("vpn-sessiondb logoff name " + str(vpntermination) + " noconfirm") #Used for vpn termination command.
print('\n******* Output for device ' + self.hostname + ' *******' )
print(self.output)
print('')
self.net_connect.disconnect()
except (NetMikoTimeoutException, NetMikoAuthenticationException) as e: #Handles timeout errors.
print("Could not connect to " + a_device.get("ip") + ", Error: ", e)
print('')
def log_result(results):
self.result_list.append(self.results)
def apply_async_with_callback(self):
self.start_time = datetime.now()
with Pool(processes=3) as self.pool:
self.results = [self.pool.apply_async(self.start_commands, args = (a_device, vpntermination), callback=self.log_result) for a_device in all_firewalls]
self.pool.close()
self.pool.join()
self.end_time = datetime.now()
self.total_time = self.end_time - self.start_time
print('\nTotal process time: ' + str(self.total_time))
def main():
#Credentials function
credentials()
root=Tk()
out_gui = OutputWindowGUI(root)
root.mainloop()
if __name__=='__main__':
freeze_support()
main()
为什么要生成线程来生成进程?正如我在开头所说的,“创建多线程(因此GUI不会冻结)”…如果您不创建线程…使用长函数…您的GUI窗口将静止并显示“无响应”。这消除了这一点。但繁殖过程也不会导致冻结。很抱歉,在这种情况下,您是不正确的。如果您在我的程序的tkinter的main循环中生成进程,它将冻结,直到这些进程完成。可能是因为您正在同步关闭/加入多进程池。您可以让它在后台运行。