Skip to main content
 首页 » 编程设计

python之一会儿听输入,并发启动一个线程

2024年10月01日9开发

  1. 我的主要代码在一个 while 循环中监听 input()。
  2. 当给出一些选项时,我需要启动一些线程并继续监听进一步的输入
  3. 但是,我无法听取输入,而且我被困在我启动的线程中。

 
while not off: 
    option = input('1. start server 2. list connected devices 3. list threads 4. stop server >') 
    print("Yout option is {}".format(option)) 
    if option is "1": 
        threading.Thread(target=start_server()).start() 
        #start_server() 
    elif option is "2": 
        connected_devices() 
    elif option is "3": 
        list_threads() 
    elif option is "4": 
        stop_server() 

请您参考如下方法:

试试这个(首先从你的新线程创建一个对象,然后从目标选项中删除(),你不能像你写的那样停止你的线程!你应该为你的程序写一个类或者你应该让每个线程 tid 和杀死他们):

import threading 
 
while True: 
    option = input('1. start server 2. list connected devices 3. list threads 4. stop server >') 
    print("Yout option is {}".format(option)) 
    if option is "1": 
        t = threading.Thread(target=start_server) 
        t.start() 
        #start_server() 
    elif option is "2": 
        connected_devices() 
    elif option is "3": 
        list_threads() 
    elif option is "4": 
        stop_server() 

祝你好运......