python - 使用用户输入不断运行 Python 脚本

标签 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() == "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 只运行一次,我希望它在程序的主线程接受用户输入时以指定的时间间隔连续运行。这是否接近我的想法,或者是否有更好的方法?

最佳答案

下面基本上就是我要找的东西。它得到了@Evert 的帮助以及位于此处的答案 How to use threading to get user input realtime while main still running in python :

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'`

关于python - 使用用户输入不断运行 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48271001/

相关文章:

python - 如何在python中绘制一条线,每个数据点都有一个间隔

python从列表中返回连续整数列表

flash - 有哪些替代方法可以将WAV循环编译为SWF?

testing - 用gradle连续测试

python - 查看 PDF 的问题

python - Python 可以静态类型化吗?

python - 从 matlab2015a 调用 python

shell - 阻止Hadoop将JobClient输出发送到命令行?

c - openssl命令行解密aes ctr 128

mysql - 如何在windows的命令行中找到mysql数据目录