在 Python 中清除一行输出
Clearing a line of output in Python
所以,我是 Python 和一般编程的超级新手。我仍在学习最基本的命令和术语。我的问题是我试图在无限循环中打印日期时间,但只在一行上。
我希望 shell 中的输出显示日期和时间,然后清除之前显示的日期时间并将其替换为新值。我似乎无法弄清楚我错过了什么,并且通过不同的问题阅读,我似乎无法找到我正在寻找的东西。任何想法、帮助或指导将不胜感激。在这一点上,尝试阅读 Python 文档对我毫无帮助。到目前为止,这是我想通的:
import datetime
import time
while True:
today = datetime.date.today()
now = datetime.datetime.now()
print ("The Current date is ", (today.strftime('%m/%d/%Y')))
print ("The Current Time is ", (now.strftime('%H:%M')))
time.sleep(30)
这会生成:
The Current date is 03/28/2017
The Current Time is 19:09
The Current date is 03/28/2017
The Current Time is 19:10
我想说:
The Current date is 03/28/2017
The Current Time is 19:09
然后,上面的文字被删除并替换为
The Current date is 03/28/2017
The Current Time is 19:10
日期时间截图
一种方法是使用 ANSI escape sequences:
import datetime
import time
import sys
while True:
today = datetime.date.today()
now = datetime.datetime.now()
print ("The Current date is ", (today.strftime('%m/%d/%Y')))
print ("The Current Time is ", (now.strftime('%H:%M')))
sys.stdout.write("3[F") # Cursor up one line
sys.stdout.write("3[F") # Cursor up one line
time.sleep(30)
另一种选择:
导入日期时间
导入时间
导入 os
while True:
today = datetime.date.today()
now = datetime.datetime.now()
print ("The Current date is ", (today.strftime('%m/%d/%Y')))
print ("The Current Time is ", (now.strftime('%H:%M')))
time.sleep(30)
os.system('clear')
所以,我是 Python 和一般编程的超级新手。我仍在学习最基本的命令和术语。我的问题是我试图在无限循环中打印日期时间,但只在一行上。
我希望 shell 中的输出显示日期和时间,然后清除之前显示的日期时间并将其替换为新值。我似乎无法弄清楚我错过了什么,并且通过不同的问题阅读,我似乎无法找到我正在寻找的东西。任何想法、帮助或指导将不胜感激。在这一点上,尝试阅读 Python 文档对我毫无帮助。到目前为止,这是我想通的:
import datetime
import time
while True:
today = datetime.date.today()
now = datetime.datetime.now()
print ("The Current date is ", (today.strftime('%m/%d/%Y')))
print ("The Current Time is ", (now.strftime('%H:%M')))
time.sleep(30)
这会生成:
The Current date is 03/28/2017
The Current Time is 19:09
The Current date is 03/28/2017
The Current Time is 19:10
我想说:
The Current date is 03/28/2017
The Current Time is 19:09
然后,上面的文字被删除并替换为
The Current date is 03/28/2017
The Current Time is 19:10
日期时间截图
一种方法是使用 ANSI escape sequences:
import datetime
import time
import sys
while True:
today = datetime.date.today()
now = datetime.datetime.now()
print ("The Current date is ", (today.strftime('%m/%d/%Y')))
print ("The Current Time is ", (now.strftime('%H:%M')))
sys.stdout.write("3[F") # Cursor up one line
sys.stdout.write("3[F") # Cursor up one line
time.sleep(30)
另一种选择:
导入日期时间 导入时间 导入 os
while True:
today = datetime.date.today()
now = datetime.datetime.now()
print ("The Current date is ", (today.strftime('%m/%d/%Y')))
print ("The Current Time is ", (now.strftime('%H:%M')))
time.sleep(30)
os.system('clear')