Bash或Python,在终端上打印字符时,如何在固定位置更改字符? [英] Bash or Python, When print characters to terminal, how to CHANGE a character at a FIXED position?

查看:82
本文介绍了Bash或Python,在终端上打印字符时,如何在固定位置更改字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在这里知道的东西应该真的是基本的",但这是我很长一段时间以来一直在思考的一个问题,不知道窍门在哪里.

The thing I want to know here should be really 'basic', but it is a question in my mind for long time and no idea where the trick is.

比方说,在一个耗时的程序( bash Python )中,我必须在运行时打印出进度的百分比,基本上我想要打印 1%,并且在一定时间后,我打印 2%等.我希望'2%'准确显示在显示'1%'的同一位置,而不是像"1%2%"之类的东西.您知道 wget ,我想要的正是wget的功能,以显示下载进度.我需要清除以前打印的字符,但是如何清除?

Let's say in a time-consuming program(either bash or Python), I have to print out the percentage of the progress when it's running, and basically I want to print 1%, and after a certain time, I print 2%, etc.. I want '2%' to be displayed exactly at the same position where '1%' was displayed, rather than they're like "1% 2%" or whatever. You know wget, what I want is exactly what wget does, to show the progress of the downloading progress. Do I need to clear the previously printed character, but how?

它基本上是如何工作的...

How does it work basically...

谢谢

推荐答案

我要用Python回答,因为它更容易.

I'm going to answer in Python, since it's easier.

您可以在终端上打印退格键,以将光标向左移动,然后写入另一个字符以覆盖当前位置.您还可以使用回车键转到行首.

You can print a backspace to the terminal to move the cursor to the left, and then write another character to overwrite the current position. You can also use a carriage return to go to the beginning of the line.

import time
import sys
for x in range(101):
    sys.stdout.write('\r%d%%' % x)
    sys.stdout.flush()
    time.sleep(0.2)
sys.stdout.write('\n')

使用回车符并重写整行是最简单的,因为您不必担心要打印多少个退格键.

Using a carriage return and rewriting the whole line is the easiest, since you don't have to be careful about how many backspaces to print.

请注意,如果新行比旧行短,则旧行仍会显示出来.

Note that if the new line is shorter than the old line, the old line will still show through.

import sys
sys.stdout.write('this is a very long line')
sys.stdout.write('\rshort line')
sys.stdout.write('\n')

输出:


short linevery long line

典型的解决方案是在长行上写空格.

A typical solution is to write spaces over the long line.

这篇关于Bash或Python,在终端上打印字符时,如何在固定位置更改字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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