更改同一 CLI 行上的文本 Python
Change text on same CLI line Python
就像一些命令行实用程序如何能够在不换行的情况下更改一行上的文本(如 curl)。我怎样才能在 Python 中做到这一点?
您可以将 sys.stdout.write
与“\r”一起使用(将光标放回行首)
演示:
>>> import sys
>>> import time
>>> while True:
... sys.stdout.write("\r"+ str(i))
... time.sleep(1)
... i+=1
...
您必须确保打印语句以回车符 return 而不是换行符结尾。对于python 2.6+,你可以用这个很傻的例子看看。
from __future__ import print_function
import time
import sys
print(".", end="\r")
sys.stdout.flush()
time.sleep(1)
print("..", end="\r")
sys.stdout.flush()
time.sleep(1)
print("...")
sys.stdout.flush()
注意:强制打印语句结束时,需要flush stdout强制显示。
就像一些命令行实用程序如何能够在不换行的情况下更改一行上的文本(如 curl)。我怎样才能在 Python 中做到这一点?
您可以将 sys.stdout.write
与“\r”一起使用(将光标放回行首)
演示:
>>> import sys
>>> import time
>>> while True:
... sys.stdout.write("\r"+ str(i))
... time.sleep(1)
... i+=1
...
您必须确保打印语句以回车符 return 而不是换行符结尾。对于python 2.6+,你可以用这个很傻的例子看看。
from __future__ import print_function
import time
import sys
print(".", end="\r")
sys.stdout.flush()
time.sleep(1)
print("..", end="\r")
sys.stdout.flush()
time.sleep(1)
print("...")
sys.stdout.flush()
注意:强制打印语句结束时,需要flush stdout强制显示。