Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

Python background loop while running other commands

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,

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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('
', SAVE_CURSOR, CSI + '0;0r', UNSAVE_CURSOR)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...