如何让python程序暂停几秒钟
可以用两个线程来做这个事情,一个线程用来发网络包,另一个线程用来接收用户输入,然后用两个全局变量控制状态。
作者:二山的小馆er 链接:https://www.zhihu.com/question/366563329/answer/2099631519 来源:知乎 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 import threading import time run = True # global variable to control whether send packet or not stop = False # global variable to control quit the program def handle_user_input(): global run, stop while True: flag = input("Input the command?(run/pause/quit)") if flag.casefold() == 'run': run = True elif flag.casefold() == 'pause': run = False elif flag.casefold() == 'quit': stop = True break else: print("Invalid command.") def fake_send_packet(): global run, stop i = 0 while True: if run: print(f"Send a packet {i}...") i += 1 if stop: break time.sleep(1) if __name__ == "__main__": th1 = threading.Thread(target=handle_user_input) th2 = threading.Thread(target=fake_send_packet) th1.start() th2.start()
输出: