Python-sys.stdout.flush()在python 2.7中的2行

13l*_*H4t 0 python stdout flush sys python-2.7

我正在用python 2.7编写

我有以下代码:

a = 0
b = 0
while True:
    a += 1
    b += 1
    print str(a)
    print str(b)
Run Code Online (Sandbox Code Playgroud)

输出如下:

1
1
2
2
3
3
4
....
Run Code Online (Sandbox Code Playgroud)

并希望用这两行冲洗stdout.flush().代码看起来像这样,但它不起作用..

import sys

a = 0
b = 0
while True:
    a += 1
    b += 1
    sys.stdout.write(str(a)+"\n")
    sys.stdout.write(str(b)+"\r")
    sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)

这会产生如下输出:

1   #1
2   #1   ->#2
3          #2   ->#3
4                 #3   ->#4
...
Run Code Online (Sandbox Code Playgroud)

我知道这是因为\r只跳到第二行的开头,然后从下一个打印开始..

如何将光标设置为第1行的开头而不是第2行?

所以它只刷新2行:

n  #1 ->#2  ->#3  ->#4  ->#.....
n  #1 ->#2  ->#3  ->#4  ->#.....
Run Code Online (Sandbox Code Playgroud)

我希望有人能理解我的意思.

gir*_*946 8

要从当前的一行转到上线,这必须写在标准输出上 \x1b[1A

CURSOR_UP_ONE = '\x1b[1A' 
Run Code Online (Sandbox Code Playgroud)

擦除行的内容\x1b[2K必须写在stdout上.

ERASE_LINE = '\x1b[2K'
Run Code Online (Sandbox Code Playgroud)

这样你就可以到达上面并覆盖那里的数据.

data_on_first_line = CURSOR_UP_ONE + ERASE_LINE + "abc\n"
sys.stdout.write(data_on_first_line)

data_on_second_line = "def\r"
sys.stdout.write(data_on_second_line)
sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请访问http://www.termsys.demon.co.uk/vtansi.htm#cursor

/sf/answers/881066721/