Kot*_*teu 7 python stdout python-3.x
我的问题是,我希望能够在python控制台中覆盖/清除以前的打印行.这个问题已被多次询问(例如,Python - 删除和替换打印项目),但是使用相同的代码(答案标记为正确,对我来说什么都没打印):
for i in range(10):
print("Loading" + "." * i)
time.sleep(1)
sys.stdout.write("\033[F") # Cursor up one line
sys.stdout.write("\033[K") # Clear to the end of line
Run Code Online (Sandbox Code Playgroud)
我得到输出(在python IDLE中):
Loading
[F[KLoading.
[F[KLoading..
[F[KLoading...
[F[KLoading....
[F[KLoading.....
[F[KLoading......
[F[KLoading.......
[F[KLoading........
[F[KLoading.........
[F[KLoading..........
[F[K
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?我google了很多,没有什么工作真的.它可以打印出任何内容,也可以不覆盖.
如果这有帮助,我运行的是Windows 8.1和Python 3.51.通过cmd运行代码不会影响任何内容.
此外,添加sys.stdout.flush()
没有帮助.
您需要从命令行运行程序,而不是从 IDLE 中运行。
然后,这应该有效:
import sys
import time
for i in range(10):
sys.stdout.write("\r" + "Loading" + "." * i)
time.sleep(1)
sys.stdout.flush()
print()
Run Code Online (Sandbox Code Playgroud)
转到\r
行的开头。因此,您必须确保打印的字符串至少与之前的字符串一样长。否则,您将看到先前打印的部分内容。
归档时间: |
|
查看次数: |
8540 次 |
最近记录: |