在python sh中运行基本数字时钟

2024-05-27 11:17:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在python shell中编写简单的数字时钟。如果可能的话,我想避免使用tkinter。这就是我现在所拥有的

import time
while True:
    from datetime import datetime
    now = datetime.now()  
    print ("%s/%s/%s %s:%s:%s" % (now.month,now.day,now.year,now.hour,now.minute,now.second)) 
    time.sleep(1)

这会产生一个重复的打印输出,就像这样

06/29/16 23:08:32

06/29/16 23:08:33

06/29/16 23:08:34

我知道这很粗糙,我还在学习。我只想要一条在外壳里有“滴答”数字时钟的线路。我在idle和windows 10上使用python 3.5.1。

如果这不可能,我很想知道为什么。

非常感谢


Tags: fromimporttruedatetimetimetkinter数字shell
3条回答

在repl.it中尝试过,这对我有效…(添加逗号now.strftime)

import time
from datetime import datetime
while True:   
    now = datetime.now()
    print (now.strftime("%m/%d/%Y %H:%M:%S"), end="", flush=True),
    print("\r", end="", flush=True),
    time.sleep(1)

你只需要:

from time import strftime
while True:
    print (strftime("%m/%d/%Y %H:%M:%S"), end="", flush=True)
    print("\r", end="", flush=True)
    time.sleep(1)

如果每次都像这样打印固定长度的输出,那么只要不打印换行符,就可以使用回车字符倒带到行的开头。示例:

# Note trailing comma, that suppresses the newline in Python
print ("%s/%s/%s %s:%s:%s" % (now.month,now.day,now.year,now.hour,now.minute,now.second)),

# Now rewind back to the start of the line. Again, not trailing comma
print("\r"),

现在,您可能还注意到屏幕上从未打印过任何内容。这是因为标准输出是缓冲的,所以您可以用它刷新:

# At the top...
import sys

# In the loop, after the first print
sys.stdout.flush()

这一切工作如下。假设屏幕上有一个光标。首先用第一次打印(和刷新)打印出时间,然后用print("\r"),将光标移回行的开头。这实际上并没有删除任何字符,只是移动光标。你下次再写一遍。因为它恰好是完全相同的长度,所以时间会再次被写出来,替换旧字符。

结果脚本如下:

import time
import sys

while True:
    from datetime import datetime
    now = datetime.now()
    print ("%s/%s/%s %s:%s:%s" % (now.month,now.day,now.year,now.hour,now.minute,now.second)),
    sys.stdout.flush()
    print("\r"),
    time.sleep(1)

如果你想对正在发生的事情进行更细粒度的控制,你可以开始使用curses库,但我认为这对于你在这里所做的工作来说是过分了。

编辑:正如注释中提到的@padraicunningham,在Python 3中禁止换行打印并强制内容刷新到屏幕的正确语法如下:

print("hello", flush=True, end="")

另外,正如@AlexHall所提到的,print语句实际上并不打印固定宽度的语句;因此,为此,我们应该使用strftime()

因此,正确的程序是:

import time

while True:
    from datetime import datetime,strftime
    now = datetime.now()
    print (strftime("%m/%d/%Y %H:%M:%S"), end="", flush=True)
    print("\r", end="", flush=True)
    time.sleep(1)

相关问题 更多 >

    热门问题