如何在终端中重写输出 [英] How to rewrite output in terminal

查看:38
本文介绍了如何在终端中重写输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python脚本,我想让它在终端中显示从0到100%的递增数字.我知道如何在终端上打印数字,但是如何才能重写"它们,以便0变成1、1变成2,依此类推直到100?

I have a Python script and I want to make it display a increasing number from 0 to 100% in the terminal. I know how to print the numbers on the terminal but how can I "rewrite" them so 0 turns into 1, 1 into 2, and so on until 100?

推荐答案

在不使用换行符的情况下打印回车符( \ r )会将光标重置为该行的开头,从而覆盖下一个打印已打印的内容:

Printing a carriage return (\r) without a newline resets the cursor to the beginning of the line, making the next print overwriting what's already printed:

import time
import sys
for i in range(100):
    print i,
    sys.stdout.flush()
    time.sleep(1)
    print "\r",

这不会清除行,因此,如果您尝试使用这种方法打印递减的数字,则会看到以前打印的剩余文本.您可以通过在输出中添加空格或在其他答案中使用某些控制代码来解决此问题.

This doesn't clear the line, so if you try to, say, print decreasing numbers using this methods, you'll see leftover text from previous prints. You can work around this by padding out your output with spaces, or using some of the control codes in the other answers.

这篇关于如何在终端中重写输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆