运行其他命令时的Python背景循环 [英] Python background loop while running other commands

查看:111
本文介绍了运行其他命令时的Python背景循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个小型迷你游戏,您每5分钟会收到一次材料. 为了监控这一点,我想编写一个简单的python脚本. 但是现在有一点路障,

I'm working on an irl minigame where you get materials every 5 minutes. To monitor this i wanted to write a simple python script. But now there is a little roadblok,

您如何创建一个每隔X分钟执行一次操作的循环,同时仍在运行其他键盘输入却不会破坏循环?

how do you make a loop that does something every x minutes, while still running other keyboard inputs without it disrupting the loop?

推荐答案

下面是使用 threading.Timer .响应用户输入时,它每5秒显示一次当前时间.

Here's a fairly simple example of using a threading.Timer. It displays the current time every 5 seconds while responding to user input.

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

This code will run in any terminal that supports ANSI / VT100 Terminal Control Escape Sequences.

#!/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,即按 Ctrl C 停止该程序,

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

这篇关于运行其他命令时的Python背景循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆