简体   繁体   English

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

[英]How to reset cursor to the beginning of the same line in Python

Most of questions related to this topics here in SO is as follows: SO中与此主题相关的大多数问题如下:

How to print some information on the same line without introducing a new line如何在不引入新行的情况下在同一行上打印一些信息

Q1 Q2 .一季度二季度

Instead, my question is as follows:相反,我的问题如下:

I expect to see the following effect,我希望看到以下效果,

>> You have finished 10%

where the 10 keep increasing in the same time.其中10不断增加。 I know how to do this in C++ but cannot find a good solution in python.我知道如何在 C++ 中做到这一点,但在 python 中找不到好的解决方案。

import sys, time

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

The \\r is the carriage return. \\r是回车。 You need the comma at the end of the print statement to avoid automatic newline.您需要在print语句末尾使用逗号以避免自动换行。 Finally sys.stdout.flush() is needed to flush the buffer out to stdout.最后需要sys.stdout.flush()将缓冲区刷新到 stdout。

For Python 3, you can use:对于 Python 3,您可以使用:

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

Python 3蟒蛇 3

You can use keyword arguments to print :您可以使用关键字参数来print

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

  • end='\\r' replaces the default end-of-line behavior with '\\r' end='\\r'替换默认结束线行为'\\r'
  • flush=True flushes the buffer, making the printed text appear immediately. flush=True刷新缓冲区,使打印的文本立即出现。

Python 2蟒蛇 2

In 2.6+ you can use from __future__ import print_function at the start of the script to enable Python 3 behavior.在 2.6+ 中,您可以在脚本开头使用from __future__ import print_function来启用 Python 3 行为。 Or use the old way:或者使用旧方法:

Python's print puts a newline after each command, unless you suppress it with a trailing comma. Python 的print在每个命令后放置一个换行符,除非您用尾随逗号取消它。 So, the print command is:所以,打印命令是:

print 'You have finished {0}%\r'.format(percentage),

Note the comma at the end.注意末尾的逗号。

Unfortunately, Python only sends the output to the terminal after a complete line.不幸的是,Python 只在完成一行后将输出发送到终端。 The above is not a complete line, so you need to flush it manually:上面不是完整的一行,所以需要手动flush一下:

import sys
sys.stdout.flush()

On linux( and probably on windows) you can use curses module like this在 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()

Benfit with curses as apposed to other simpler technique is that, you can draw on terminal like a graphics program, because curses provides moving to any x,y position eg below is a simple script which updates four views与其他更简单的技术相比,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()

使用sys.stdout.write()而不是 print 在 python 2 和 3 中都可以工作,没有任何妥协。

I had to combine a few answers above to make it work on Python 3.7 / Windows 10. The example runs on Spyder's console:我必须结合上面的几个答案才能使其在 Python 3.7/Windows 10 上运行。该示例在 Spyder 的控制台上运行:

import sys, time

for i in range(0, 101, 5):
  print("\r>> You have finished {}%".format(i), end='')
  sys.stdout.flush()
  time.sleep(.2)

The time.sleep(.2) is just used to simulates some time-consuming code. time.sleep(.2)只是用来模拟一些耗时的代码。

The OP didn't specify Py2 or Py3. OP 没有指定 Py2 或 Py3。 In Python 3 the 'import' of 'sys' and the 'sys.stdout' call can be replaced with 'flush=True':在 Python 3 中,'sys' 的 'import' 和 'sys.stdout' 调用可以替换为 'flush=True':

import time
for i in range(0,101,25):
  print("\r>>TESTING - {:0>3d}%".format(i), end='', flush=True)
  time.sleep(.5)
print()

Thanks to Petr Viktorin for showing the "flush" parameter for Python 3 print().感谢Petr Viktorin展示了 Python 3 print() 的“flush”参数。 I submit this because his Python 3 example doesn't include a 'format' specifier.我提交这个是因为他的 Python 3 示例不包含“格式”说明符。 It took me awhile to figure out that the additional parameters go after the 'format' specifier parentheses as shown in my example.我花了一段时间才弄清楚附加参数“格式”说明符括号之后,如我的示例所示。 I just picked an example format of 3 character integer 0 filled on the left.我刚刚选择了一个示例格式,在左侧填充了 3 个字符的整数 0。 The best doc I found for Py3 format is: 6.1.3.1.我为 Py3 格式找到的最好的文档是: 6.1.3.1。 Format Specification Mini-Language 格式规范迷你语言

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM