【问题标题】:Python background loop while running other commands运行其他命令时的Python后台循环
【发布时间】:2017-07-16 16:25:51
【问题描述】:

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

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

【问题讨论】:

  • 提供您的源代码(或至少提供相关部分)
  • 首先阅读本文,了解如何通过以下链接提出问题stackoverflow.com/help/asking
  • 我们不应该在这里提供关于 SO 的教程,但让我打破规则。您可能需要阅读有关将代码组织成 threads 的内容。其中一个线程会每五分钟唤醒一次并做一些事情。另一个线程似乎会持续运行以处理键盘和鼠标事件。

标签: python loops


【解决方案1】:

这是一个使用threading.Timer 的相当简单的示例。它在响应用户输入时每 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停止这个程序,

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 您链接到古老的 Python 2.4 文档有什么特别的原因吗?最新版本是here
    • 是我的错误,我没有意识到它是针对 Python 2.x 的;下次我要链接到哪个版本时,我会格外小心。不过思路是一样的,我相信这是解决问题的好办法
    猜你喜欢
    • 2021-07-31
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 2012-10-16
    • 2015-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多