python怎么背景实现循环_运行其他命令时的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,

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

解决方案

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值