如何讓python程式暫停幾秒鐘
阿新 • • 發佈:2022-05-30
可以用兩個執行緒來做這個事情,一個執行緒用來發網路包,另一個執行緒用來接收使用者輸入,然後用兩個全域性變數控制狀態。
作者:二山的小館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()
輸出: