运行其他命令时的 Python 后台循环



我正在做一个irl小游戏,你每5分钟就能得到一次材料。 为了监控这一点,我想写一个简单的python脚本。 但是现在有一个小路人,

如何制作一个每 X 分钟执行一次操作的循环,同时仍然运行其他键盘输入而不会中断循环?

下面是一个使用线程的相当简单的示例。定时器。它每 5 秒显示一次当前时间,同时响应用户输入。

此代码将在支持 ANSI/VT100 终端控制转义序列的任何终端中运行。

#!/usr/bin/env python3
''' Scrolling Timer
Use a threading Timer loop to display the current time
while processing user input
See https://stackoverflow.com/q/45130837/4014959
Written by PM 2Ring 2017.07.18
'''
import readline
from time import ctime
from threading import Timer
# Some ANSI/VT100 Terminal Control Escape Sequences
CSI = 'x1b['
CLEAR = CSI + '2J'
CLEAR_LINE = CSI + '2K'
SAVE_CURSOR = CSI + 's'
UNSAVE_CURSOR = CSI + 'u'
GOTO_LINE = CSI + '%d;0H'
def emit(*args):
print(*args, sep='', end='', flush=True)
# Show the current time in the top line using a Timer thread loop
def show_time(interval):
global timer
emit(SAVE_CURSOR, GOTO_LINE % 1, CLEAR_LINE, ctime(), UNSAVE_CURSOR)
timer = Timer(interval, show_time, (interval,))
timer.start()
# Set up scrolling, leaving the top line fixed
emit(CLEAR, CSI + '2;r', GOTO_LINE % 2)
# Start the timer loop
show_time(interval=5)
try:
while True:
# Get user input and print it in upper case
print(input('> ').upper())
except KeyboardInterrupt:
timer.cancel()
# Cancel scrolling
emit('n', SAVE_CURSOR, CSI + '0;0r', UNSAVE_CURSOR)

你需要发送一个KeyboardInterrupt,即按CtrlC停止这个程序,

也许计时器会对您的任务有所帮助。我建议您查看此链接:https://docs.python.org/2.4/lib/timer-objects.html。当计时器计数时,您可以执行其他任务,当时间结束时,您可以将函数附加到计时器以执行某些操作。此库中的计时器继承自线程

最新更新