【发布时间】:2018-01-15 21:37:13
【问题描述】:
我想编写一个 python 命令行脚本,该脚本将接受用户输入,同时以恒定的时间间隔运行另一个函数或脚本。我在下面写了一些伪代码来展示我的目标:
def main():
threading.Timer(1.0, function_to_run_in_background).start()
while True:
command = raw_input("Enter a command >>")
if command.lower() == "quit":
break
def function_to_run_in_background():
while True:
print "HI"
time.sleep(2.0)
if __name__ == "__main__":
main()
我试图按照这些思路来做一些事情,但通常发生的情况是 function_to_run_in_background 只运行一次,我希望它在程序的主线程接受用户输入时以指定的时间间隔连续运行。这与我的想法接近还是有更好的方法?
【问题讨论】:
-
你有什么问题?
-
function_to_run_in_background应该只运行一次(延迟 2 秒)还是每 2 秒运行一次? -
根据我的澄清编辑,我希望
function_to_run_in_background每 2 秒运行一次。 -
Timer根据文档仅运行一次(在您的情况下为 2 秒后)。 -
一个简单的替代方法是创建一个线程(没有计时器),它本身运行一个无限的while循环,具有睡眠功能。这不会每 2 秒运行一次您的函数,因为函数本身需要时间,但它可能会接近您想要的。 (
sched.scheduler可能会有所帮助。)
标签: python command-line continuous