Aar*_*lla 18 python windows command-line overwrite carriage-return
在Unix上,我可以使用\ r(回车)或\ b(退格)来打印在shell中已经可见的文本(即再次覆盖当前行).
我可以从Python脚本在Windows命令行中实现相同的效果吗?
我尝试了curses模块,但它似乎在Windows上不可用.
nos*_*klo 28
是:
import sys
import time
def restart_line():
sys.stdout.write('\r')
sys.stdout.flush()
sys.stdout.write('some data')
sys.stdout.flush()
time.sleep(2) # wait 2 seconds...
restart_line()
sys.stdout.write('other different data')
sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)
Hon*_*.Wu 12
import sys
import time
for i in range(10):
print '\r', # print is Ok, and comma is needed.
time.sleep(0.3)
print i,
sys.stdout.flush() # flush is needed.
Run Code Online (Sandbox Code Playgroud)
如果在IPython-notebook上,就像这样:
import time
from IPython.display import clear_output
for i in range(10):
time.sleep(0.25)
print(i)
clear_output(wait=True)
Run Code Online (Sandbox Code Playgroud)
我知道这是旧的,但我想告诉我的版本(它在我的电脑上在cmd中运行,但不在空闲状态下)来覆盖Python 3中的一行:
>>> from time import sleep
>>> for i in range(400):
>>> print("\r" + str(i), end="")
>>> sleep(0.5)
Run Code Online (Sandbox Code Playgroud)
编辑: 它适用于Windows和Ubuntu
我刚遇到这个问题.您仍然可以使用\r,即使在Windows命令提示符中,它只会将您带回到上一个换行符(\n).
如果您这样做:
cnt = 0
print str(cnt)
while True:
cnt += 1
print "\r" + str(cnt)
Run Code Online (Sandbox Code Playgroud)
你会得到:
0
1
2
3
4
5
...
Run Code Online (Sandbox Code Playgroud)
那是因为\r只回到最后一行.由于您已使用最后一个print语句编写了换行符,因此光标从新的空行开始到同一个新空行的开头.
为了说明,在打印第一个0后,您的光标将在此处:
0
| # <-- Cursor
Run Code Online (Sandbox Code Playgroud)
当你\r,你去了线的开头.但是你已经开始了.
修复是为了避免打印\n字符,因此光标位于同一行并\r正确覆盖文本.你可以这样做print 'text',.逗号可以阻止打印换行符.
cnt = 0
print str(cnt),
while True:
cnt += 1
print "\r" + str(cnt),
Run Code Online (Sandbox Code Playgroud)
现在它将正确地重写行.
请注意,这是Python 2.7,因此是print语句.
简单的方法:)
import sys
from time import sleep
import os
#print("\033[y coordinate;[x coordinateH Hello")
os.system('cls')
sleep(0.2)
print("\033[1;1H[]")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H[]")
sleep(0.2)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40969 次 |
| 最近记录: |