如何将光标重置到Python中同一行的开头

q09*_*987 27 python

SO中与此主题相关的大多数问题如下:

如何在不引入新行的情况下在同一行上打印一些信息

Q1 Q2.

相反,我的问题如下:

我希望看到以下效果,

>> You have finished 10%
Run Code Online (Sandbox Code Playgroud)

在那里10不断增加的同时.我知道如何在C++中做到这一点,但在python中找不到一个好的解决方案.

NPE*_*NPE 30

import sys, time

for i in xrange(0, 101, 10):
  print '\r>> You have finished %d%%' % i,
  sys.stdout.flush()
  time.sleep(2)
print
Run Code Online (Sandbox Code Playgroud)

\r是回车.您需要在print语句末尾使用逗号以避免自动换行.最后sys.stdout.flush()需要将缓冲区刷新到stdout.

对于Python 3,您可以使用:

print("\r>> You have finished {}%".format(i), end='')
Run Code Online (Sandbox Code Playgroud)


Pet*_*rin 15

Python 3

您可以使用关键字参数print:

print('string', end='\r', flush=True)

  • end='\r' 用.替换默认的行尾行为 '\r'
  • flush=True 刷新缓冲区,使打印的文本立即显示.

Python 2

在2.6+中,您可以from __future__ import print_function在脚本的开头使用它来启用Python 3行为.或者使用旧方式:

Python print在每个命令之后放置一个换行符,除非你用尾随逗号来压缩它.所以,打印命令是:

print 'You have finished {0}%\r'.format(percentage),
Run Code Online (Sandbox Code Playgroud)

注意最后的逗号.

不幸的是,Python只在完整的一行之后将输出发送到终端.以上不是一个完整的行,所以你需要flush手动:

import sys
sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)


Anu*_*yal 6

在linux(可能还有windows)上,你可以像这样使用curses模块

import time
import curses

win = curses.initscr()
for i in range(100):
    win.clear()
    win.addstr("You have finished %d%%"%i)
    win.refresh()
    time.sleep(.1)
curses.endwin()
Run Code Online (Sandbox Code Playgroud)

与其他更简单的技术相比,curses 的好处在于,您可以像图形程序一样在终端上绘图,因为curses 提供移动到任何 x,y 位置的功能,例如下面是一个更新四个视图的简单脚本

import time
import curses

curses.initscr()

rows = 10
cols= 30
winlist = []
for r in range(2):
    for c in range(2):
        win = curses.newwin(rows, cols, r*rows, c*cols)
        win.clear()
        win.border()
        winlist.append(win)

for i in range(100):
    for win in winlist:
        win.addstr(5,5,"You have finished - %d%%"%i)
        win.refresh()
    time.sleep(.05)
curses.endwin()
Run Code Online (Sandbox Code Playgroud)