等待用户输入或按定义的时间间隔运行的程序?

Program that either waits for user input or runs at defined intervals?

我目前有一个定期运行的程序。现在程序连续运行,每 30 分钟检查一次新文件:

def filechecker():
    #check for new files in a directory and do stuff

while True:
    filechecker()
    print '{} : Sleeping...press Ctrl+C to stop.'.format(time.ctime())
    time.sleep(1800)

但是,我也希望用户能够来到终端并输入击键以手动调用 filechecker(),而不是等待程序从睡眠中唤醒或不得不重新启动程序。这可能吗?我试着看看使用线程,但我真的不知道如何将计算机从睡眠中唤醒(没有太多线程经验)。

我知道我可以轻松做到:

while True:
    filechecker()
    raw_input('Press any key to continue')

完全手动控制,但我希望我的蛋糕也能吃。

你可以通过按 ctrl+c filechecker() 来 运行 使用这个:

def filechecker():
    #check for new files in a directory and do stuff

filechecker()
while True:
    print '{} : Sleeping...press Ctrl+C to run manually.'.format(time.ctime())
    try:
        time.sleep(1800)
    except KeyboardInterrupt:
        filechecker()
   filechecker()

您可以使用带有 KeyboardInterrupt 的 try/except 块(这是您在 time.sleep() 中使用 Ctrl-C 得到的结果。然后在除此之外,询问用户是否想要立即退出或 运行 filechecker。 喜欢:

while True:
    filechecker()
    try:
        print '{0} : Sleeping...press Ctrl+C to stop.'.format(time.ctime())
        time.sleep(10)
    except KeyboardInterrupt:
        input = raw_input('Got keyboard interrupt, to exit press Q, to run, press anything else\n')
        if input.lower() == 'q':
            break

clindseysmith 提供的解决方案比原始问题要求的按键多了一个按键(至少,我的解释是这样)。如果你真的想结合问题中两个代码片段的效果,即你不想按 Ctrl+C 立即调用文件检查器,你可以这样做:

import time, threading

def filechecker():
    #check for new files in a directory and do stuff
    print "{} : called!".format(time.ctime())

INTERVAL = 5 or 1800
t = None

def schedule():
    filechecker()
    global t
    t = threading.Timer(INTERVAL, schedule)
    t.start()

try:
    while True:
        schedule()
        print '{} : Sleeping... Press Ctrl+C or Enter!'.format(time.ctime())
        i = raw_input()
        t.cancel()
except KeyboardInterrupt:
    print '{} : Stopped.'.format(time.ctime())
    if t: t.cancel()

变量t 保存了被调度的下一个调用文件检查器的线程的id。按 Enter 取消 t 并重新安排。按 Ctrl-C 取消 t 并停止。