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