随笔 - 1762  文章 - 0  评论 - 109  阅读 - 431万

如何让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()
复制代码

输出:

 

posted on   一杯明月  阅读(1183)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
历史上的今天:
2021-05-30 pdf转图片
2021-05-30 心流
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示