nessus 命令行新建用户_python实现cli命令行的进度条光标滚动显示效果

python实现cli命令行的进度条光标滚动显示效果,

python如何实现cli命令行的光标滚动效果?我们在制作cli工具的时候,会遇到如果比较长时间执行的任务,可能需要类似progress进度的功能,这样用户使用的时候会比较友好。这篇文章主要是使python来实现这样的效果。

主要借助Thread lib,在执行长时间运行任务的时候,新建一个Thread在后台持续往控制台输出光标。

在使用Thread的时候需要注意意外退出情况下停止Thread,将Thread的daemon设置为True,这样子在退出python进程的情况下同时退出Thread子进程

代码运行效果如图所示:

fd5917e9ec04e45de5ed7f6e24140201.gif

下面直接上代码,使用的都是python标准库,最后有实际使用的例子代码:

import sys
import time
from threading import Thread


class ProgressThread(Thread):
    def __init__(self):
        super(ProgressThread, self).__init__()
        self.is_stop = False
        self.cursor_index = 0
        self.cursor_str = '|/-'
        self.now = None
        self.info = ""

    def set_progress_info(self, info):
        self.info = info

    def get_progress_text(self):
        cursor = self.cursor_str[self.cursor_index]
        self.cursor_index = self.cursor_index + 1
        if self.cursor_index == len(self.cursor_str):
            self.cursor_index = 0
        time_second = str(int(time.time() - self.now))
        progress_text = self.info + " " + time_second + "s " + cursor
        return progress_text

    def stop_progress(self):
        self.is_stop = True
        time.sleep(0.6)

    def run(self):
        self.now = time.time()
        while True:
            if not self.is_stop:
                progress_text = self.get_progress_text()
                sys.stdout.write(progress_text)
                sys.stdout.flush()
                time.sleep(0.4)
                sys.stdout.write('r')
            else:
                return


class Progress:

    def __init__(self):
        self.current_thread = None
        pass

    def start_progress(self, progress_info):
        if self.current_thread is not None:
            self.current_thread.stop_progress()
        self.current_thread = ProgressThread()
        self.current_thread.daemon = True
        self.current_thread.set_progress_info(progress_info)
        self.current_thread.start()

    def stop_progress(self):
        if self.current_thread is not None:
            self.current_thread.stop_progress()
        self.current_thread = None

    def show_progress(self, info):
        self.current_thread.set_progress_info(info)


if __name__ == '__main__':
    progress = Progress()
    progress.start_progress("开始上传文件")
    for i in range(10):
        time.sleep(0.5)
        progress.show_progress("文件上传中")
    progress.stop_progress()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值