python函数执行时间长,shell终端加载转圈动画

行云流水
2022-04-11 / 0 评论 / 1,116 阅读 / 正在检测是否收录...

前言

今天在写服务器测试脚本的过程中,自己用python调用shell脚本测试磁盘I/O,并输出测试结果。测试磁盘IO等待时间比较长,大约有10几分钟。因为远程ssh链接,长时间的等待,也不知道是不是网络中断了,于是想加一个加载动画。

一开始想加一个进度条,找了好多教程,写的都比较简单,一个for循环,然后输出进度条。折腾了半天感觉也不符合要求。折腾了几个小时,总算搞定。在此记录一下。

功能代码

import _thread
import time

def loading(lock):
    """
    等待函数
    """
    chars = ['⣾', '⣷', '⣯', '⣟', '⡿', '⢿', '⣻', '⣽']
    i = 0
    print('')
    while lock[0]:
        i = (i+1) % len(chars)
        print('\033[A%s %s' %
              (chars[i], lock[1] or '' if len(lock) >= 2 else ''))
        time.sleep(0.25)
    print('')

使用

def get_result_by_shell(key, bashpath):
    """
    调用shell脚本获取数据
    """
    #显示执行动画...
    lock = [True, '正在获取:{}...'.format(key)]
    try:
        _thread.start_new_thread(loading, (lock,))
    except Exception as e:
        print(e)

    status, output = subprocess.getstatusoutput('bash {}'.format(bashpath))
    print(status)
    print(output)
  
    lock[0] = False

参考

Python控制台加载中转圈动画

评论 (0)

取消
只有登录/注册用户才可评论