替换Python中的控制台输出

发布于 2021-01-29 19:30:31

我想知道如何像某些C / C ++程序那样在Python中创建这些漂亮的控制台计数器之一。

我在做一个循环,当前输出如下:

Doing thing 0
Doing thing 1
Doing thing 2
...

更整洁的是只更新最后一行;

X things done.

我已经在许多控制台程序中看到了这一点,并且想知道是否/如何在Python中做到这一点。

关注者
0
被浏览
178
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    一个简单的解决方案是只"\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()



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看