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

2024-01-11

我正在开发一款现实迷你游戏,每 5 分钟就会获得一次材料。 为了监控这一点,我想编写一个简单的 python 脚本。 但现在有一个小障碍,

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


这是一个相当简单的使用示例线程.定时器 https://docs.python.org/3/library/threading.html#timer-objects。它在响应用户输入的同时每 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)

You need to send a KeyboardInterrupt, that is, hit CtrlC to stop this program,

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

运行其他命令时的 Python 后台循环 的相关文章

随机推荐