2017-03-29 82 views
0

所以,我对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 

日期时间截图

+0

对于那些没有注意到的人来说这是RaspberryPi –

回答

0

一种方法是使用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("\033[F") # Cursor up one line 
    sys.stdout.write("\033[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') 
+0

谢谢。当我插入它时,显示器产生如下输出: ''当前时间是08:18 [F [F当前日期是03/29/2017 当前时间是08:19 [F [F当前日期为2017年3月29日 当前时间为08:19 [F [F'' –

+0

什么是您的操作系统? – eyllanesc

+0

好问题。我有一个raspbian安装程序和一个Windows安装程序。我正在运行Win7。在Pyton Shell中运行时,我认为操作系统并不重要。可以? –