是否有一种方法,例如,打印Hello World!每n秒? 例如,程序将遍历我所拥有的任何代码,然后在5秒后(使用time.sleep())执行该代码。我会用这个来更新文件,而不是打印Hello World。

例如:

startrepeat("print('Hello World')", .01) # Repeats print('Hello World') ever .01 seconds

for i in range(5):
    print(i)

>> Hello World!
>> 0
>> 1
>> 2
>> Hello World!
>> 3
>> Hello World!
>> 4

当前回答

import threading

def printit():
  threading.Timer(5.0, printit).start()
  print "Hello, World!"

printit()

# continue with the rest of your code

https://docs.python.org/3/library/threading.html#timer-objects

其他回答

你可以启动一个单独的线程,它的唯一职责是数5秒,更新文件,重复。您不希望这个单独的线程干扰主线程。

def update():
    import time
    while True:
        print 'Hello World!'
        time.sleep(5)

它会作为函数运行。while True:让它永远运行。如果需要,你可以把它从函数中提出来。

下面是一个不需要每n秒创建一个新线程的版本:

from threading import Event, Thread

def call_repeatedly(interval, func, *args):
    stopped = Event()
    def loop():
        while not stopped.wait(interval): # the first call is in `interval` secs
            func(*args)
    Thread(target=loop).start()    
    return stopped.set

该事件用于停止重复:

cancel_future_calls = call_repeatedly(5, print, "Hello, World")
# do something else here...
cancel_future_calls() # stop future calls

请参见改进setInterval python的当前实现

为自己省下一次精神分裂发作,使用高级Python调度器: http://pythonhosted.org/APScheduler

代码非常简单:

from apscheduler.scheduler import Scheduler

sched = Scheduler()
sched.start()

def some_job():
    print "Every 10 seconds"

sched.add_interval_job(some_job, seconds = 10)

....
sched.shutdown()
import threading

def printit():
  threading.Timer(5.0, printit).start()
  print "Hello, World!"

printit()

# continue with the rest of your code

https://docs.python.org/3/library/threading.html#timer-objects