2024-04-25 16:53:19 发布
网友
我有一个循环在做一些事情,电流输出是沿着:
Doing thing 0 Doing thing 1 Doing thing 2 ...
更整洁的做法是更新最后一行代码
X things done.
我在许多控制台程序中都看到过这一点,我想知道是否/如何在Python中做到这一点。
另一个答案可能更好,但我正在做的是。首先,我制作了一个名为progress的函数,它可以打印退格字符:
def progress(x): out = '%s things done' % x # The output bs = '\b' * 1000 # The backspace print bs, print out,
然后我在主函数中循环调用它,如下所示:
def main(): for x in range(20): progress(x) return
这当然会删除整行,但你可以把它弄乱,做你想做的事情。我最终用这种方法取得了进步。
一个更优雅的解决方案可能是:
def progressBar(value, endvalue, bar_length=20): percent = float(value) / endvalue arrow = '-' * int(round(percent * bar_length)-1) + '>' spaces = ' ' * (bar_length - len(arrow)) sys.stdout.write("\rPercent: [{0}] {1}%".format(arrow + spaces, int(round(percent * 100)))) sys.stdout.flush()
用value和endvalue调用此函数,结果应该是
value
endvalue
Percent: [-------------> ] 69%
一个简单的解决方案是在字符串前面写"\r",而不是添加换行符;如果字符串永远不会变短,这就足够了。。。
"\r"
sys.stdout.write("\rDoing thing %i" % i) sys.stdout.flush()
稍微复杂一点的是进度条。。。这是我用的东西:
def startProgress(title): global progress_x sys.stdout.write(title + ": [" + "-"*40 + "]" + chr(8)*41) sys.stdout.flush() progress_x = 0 def progress(x): global progress_x x = int(x * 40 // 100) sys.stdout.write("#" * (x - progress_x)) sys.stdout.flush() progress_x = x def endProgress(): sys.stdout.write("#" * (40 - progress_x) + "]\n") sys.stdout.flush()
通过操作描述调用startProgress,然后progress(x),其中x是百分比,最后是endProgress()
startProgress
progress(x)
x
endProgress()
另一个答案可能更好,但我正在做的是。首先,我制作了一个名为progress的函数,它可以打印退格字符:
然后我在主函数中循环调用它,如下所示:
这当然会删除整行,但你可以把它弄乱,做你想做的事情。我最终用这种方法取得了进步。
一个更优雅的解决方案可能是:
用
value
和endvalue
调用此函数,结果应该是一个简单的解决方案是在字符串前面写
"\r"
,而不是添加换行符;如果字符串永远不会变短,这就足够了。。。稍微复杂一点的是进度条。。。这是我用的东西:
通过操作描述调用
startProgress
,然后progress(x)
,其中x
是百分比,最后是endProgress()
相关问题 更多 >
编程相关推荐