Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用用户输入持续运行Python脚本_Python_Command Line_Continuous - Fatal编程技术网

使用用户输入持续运行Python脚本

使用用户输入持续运行Python脚本,python,command-line,continuous,Python,Command Line,Continuous,我想编写一个python命令行脚本,它将接受用户输入,同时以固定的时间间隔运行另一个函数或脚本。我在下面编写了一些伪代码来说明我的目标: def main(): threading.Timer(1.0, function_to_run_in_background).start() while True: command = raw_input("Enter a command >>") if command.lower() == "

我想编写一个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()

我已经尝试过让这些东西工作,但通常情况下,函数在后台只运行一次,我希望它在程序的主线程接受用户输入时以指定的间隔连续运行。这是接近我的想法还是有更好的方法?

下面就是我想要的。@Evert以及此处的答案帮助了我们:


你的问题是什么?应该只在后台运行一次(延迟2秒)还是每2秒运行一次?根据我的澄清编辑,我希望在后台运行一次。
定时器只运行一次(在你的情况下,在2秒之后),根据文档,一个简单的替代方法是创建一个线程(没有计时器),该线程本身运行一个无限while循环,并带有一个sleep函数。这不会完全每2秒运行一次函数,因为函数本身需要时间,但它可能会接近您想要的。(
sched.scheduler
可能会有所帮助。)
import threading
import time
import sys

def background():
    while True:
        time.sleep(3)
        print 'disarm me by typing disarm'


def save_state():
    print 'Saving current state...\nQuitting Plutus. Goodbye!'

# now threading1 runs regardless of user input
threading1 = threading.Thread(target=background)
threading1.daemon = True
threading1.start()

while True:
    if raw_input().lower() == 'quit':
        save_state()
        sys.exit()
    else:
        print 'not disarmed'`