终端中带有块字符的文本进度条
简介
在终端中创建进度条可以通过提供视觉效果来极大地增强用户体验任务进度的表示。然而,在更新进度条的同时保持先前控制台输出的完整性可能是一个挑战。本文探讨了如何在 Python 中创建进度条,同时保留先前的文本。
解决方案:自定义进度条函数
这里有一个可重用的进度条函数,可以解决该问题:
def printProgressBar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█', printEnd='\r'): percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total))) filledLength = int(length * iteration // total) bar = fill * filledLength + '-' * (length - filledLength) print(f'\r{prefix} |{bar}| {percent}% {suffix}', end=printEnd) if iteration == total: print()
功能参数:
Parameter | Description |
---|---|
iteration | Current iteration of the loop |
total | Total number of iterations |
prefix | Prefix text before the progress bar |
suffix | Suffix text after the progress bar |
decimals | Number of decimal places for percentage |
length | Width of the progress bar |
fill | Character used to fill the progress bar |
printEnd | End of line character (e.g., 'r') |
用法:
要使用进度条,请在循环内调用该函数:
total_items = 100 for item in range(total_items): # Do your processing here... printProgressBar(item + 1, total_items)
单次调用版本:
对于简化的用例,请考虑这个单次调用版本的进度bar:
def progressBar(iterable, prefix='', suffix='', decimals=1, length=100, fill='█', printEnd='\r'): total = len(iterable) def printProgressBar(iteration): percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total))) 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() for item in progressBar(range(100)): # Do your processing here...
此版本不需要初始调用即可将进度条设置为 0%,并接受可迭代作为输入。
Python 2 兼容性:
对于 Python 2兼容性,使用以下代码代替Python 3字符串格式:
print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end=printEnd)
结论:
通过利用提供的功能,您可以轻松地将文本进度条集成到控制台应用程序中,同时避免删除先前的文本。可自定义的参数允许定制适合您特定要求的进度条外观。
以上是如何使用 Python 在终端中创建文本进度条?的详细内容。更多信息请关注PHP中文网其他相关文章!

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

concateNateListsinpythonwithTheSamelements,使用:1)operatototakeepduplicates,2)asettoremavelemavphicates,or3)listCompreanspearensionforcontroloverduplicates,每个methodhasdhasdifferentperferentperferentperforentperforentperforentperfortenceandordormplications。

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允许ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能