【问题标题】:Constantly Running Python Script With User Input使用用户输入不断运行 Python 脚本
【发布时间】: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


【解决方案1】:

下面基本上是我正在寻找的。 @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'`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    相关资源
    最近更新 更多