import time
import sys
def backspace(n):
sys.stdout.write((b'\x08' * n).decode()) # use \x08 char to go back
for i in range(101): # for 0 to 100
s = str(i) + '%' # string for output
sys.stdout.write(s) # just print
sys.stdout.flush() # needed for flush when using \x08
backspace(len(s)) # back n chars
time.sleep(0.2) # sleep for 200ms
Python3:
import time
def backline():
print('\r', end='') # use '\r' to go back
for i in range(101): # for 0 to 100
s = str(i) + '%' # string for output
print(s, end='') # just print and flush
backline() # back to the beginning of line
time.sleep(0.2) # sleep for 200ms
您可以使用
print
语句来执行此操作,而无需导入sys
。print
行末尾的逗号防止print
发出新行(您应该注意,输出末尾将有额外的空格)。Python3解决方案 由于上述操作在Python 3中不起作用,因此您可以这样做(同样,不导入
sys
):print函数接受默认为
"\n"
的end
参数。将其设置为空字符串可防止它在行尾发出新行。您只需使用:
输出将是
不需要通过
import sys
过度杀戮。注意结尾的逗号符号。Python3+
print("some string", end="");
删除末尾的换行符。阅读更多help(print);
您应该使用backspace'\r'或('\x08')字符返回控制台输出中的上一个位置
Python2+:
Python3:
此代码将在一行上从0%计数到100%。最终价值为:
这里有关于flush的其他信息:Why do python print statements that contain 'end=' arguments behave differently in while-loops?
相关问题 更多 >
编程相关推荐