问题:
在控制台应用程序中,如何显示进度bar 使用 ftplib 上传或下载文件,不会干扰之前打印的内容
解决方案:
要创建在保留控制台输出的同时更新的可自定义进度条,请考虑以下内容:
选项 1 :单次调用
def progressBar(iterable, prefix="", suffix="", decimals=1, length=100, fill="█", printEnd="\r"): """ Single-call progress bar function. Args: iterable (Iterable): Iteratable object. prefix (str): Prefix string. suffix (str): Suffix string. decimals (int): Number of decimals in percent complete. length (int): Character length of bar. fill (str): Fill character. printEnd (str): End character. """ total = len(iterable) def printProgressBar(iteration): percent = "{0:.{1}f}".format(100 * (iteration / float(total)), decimals) filledLength = int(length * iteration // total) bar = fill * filledLength + "-" * (length - filledLength) print(f"\r{prefix} |{bar}| {percent}% {suffix}", end=printEnd) printProgressBar(0) for i, item in enumerate(iterable): yield item printProgressBar(i + 1) print()
示例用法:
import time items = list(range(57)) for item in progressBar(items, prefix="Progress:", suffix="Complete", length=50): # Do stuff... time.sleep(0.1)
选项 2:多次调用
def printProgressBar(iteration, total, prefix="", suffix="", decimals=1, length=100, fill="█", printEnd="\r"): """ Progress bar printing function. Args: iteration (int): Current iteration. total (int): Total iterations. prefix (str): Prefix string. suffix (str): Suffix string. decimals (int): Number of decimals in percent complete. length (int): Character length of bar. fill (str): Fill character. printEnd (str): End character. """ percent = "{0:.{1}f}".format(100 * (iteration / float(total)), decimals) filledLength = int(length * iteration // total) bar = fill * filledLength + "-" * (length - filledLength) print(f"\r{prefix} |{bar}| {percent}% {suffix}", end=printEnd) if iteration == total: print()
用法示例:
import time items = list(range(57)) # Initial call to print 0% progress printProgressBar(0, len(items), prefix="Progress:", suffix="Complete", length=50) for i, item in enumerate(items): # Do stuff... time.sleep(0.1) printProgressBar(i + 1, len(items), prefix="Progress:", suffix="Complete", length=50)
两个选项都提供可自定义的进度条,可以动态更新而不会覆盖之前的控制台输出。
以上是如何在 Python 中创建可自定义的终端文本进度条而不覆盖以前的输出?的详细内容。更多信息请关注PHP中文网其他相关文章!