日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python控制命令行光标位置_python实现cli命令行的进度条光标滚动显示效果

發布時間:2025/3/15 python 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python控制命令行光标位置_python实现cli命令行的进度条光标滚动显示效果 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

python實現cli命令行的進度條光標滾動顯示效果,

python如何實現cli命令行的光標滾動效果?我們在制作cli工具的時候,會遇到如果比較長時間執行的任務,可能需要類似progress進度的功能,這樣用戶使用的時候會比較友好。這篇文章主要是使python來實現這樣的效果。

主要借助Thread lib,在執行長時間運行任務的時候,新建一個Thread在后臺持續往控制臺輸出光標。

在使用Thread的時候需要注意意外退出情況下停止Thread,將Thread的daemon設置為True,這樣子在退出python進程的情況下同時退出Thread子進程

代碼運行效果如圖所示:

下面直接上代碼,使用的都是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()

總結

以上是生活随笔為你收集整理的python控制命令行光标位置_python实现cli命令行的进度条光标滚动显示效果的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。