Pythonの時限入力

Oct 14 2020

私は、ユーザーが特定の時間内に入力を送信する必要があるPythonゲームボットを書いています。

これの現在の実装は、その時間スリープする新しいスレッドを生成し、入力が送信されたかどうかを確認することです。別のスレッドが開始した後に時間がなくなり、if chatid in user_threadsパーツがtrueと評価される可能性があるため、ナンスが追加されます。この方法を使用する必要がありますか、それとも時間指定の入力を行うためのより良い解決策がありますか(競合状態のようなために失敗する可能性が低いという意味で)。

私も使ってみましたmultiprocessing.Processが、他のプロセスと変数を共有するのはもっと面倒なようです。

from threading import Thread
from time import time, sleep
from random import randint

user_threads = {}

def timeout(t,r):
    while time()-t<5:
        sleep(5-time()+t)
    if chatid in user_threads:
        if user_threads[chatid][3] != r:
            return
        del user_threads[chatid]
        print("Too slow")

def recvans(ans,inp):
    if ans==inp:
        print("yes")
    else:
        print("no")

def starttimer(chatid):
    r = randint(0,1<<128)
    user_threads[chatid] = [None,None,None,r]
    user_threads[chatid][2] = ["a"]
    P = Thread(target = timeout, args = (time(),r))
    user_threads[chatid][0] = P
    user_threads[chatid][1] = recvans
    P.start()

while True: # simulating user input from different users (here chatid=1)
    inp = input()
    chatid = 1
    if chatid in user_threads:
        t, func, args, _ = user_threads[chatid]
        if t == None:
            print("Please wait")
            continue
        del user_threads[chatid]
        args += [inp]
        func(*args)
        continue
    if inp == "Start":
        starttimer(chatid)
        continue
    if inp == "Quit":
        break
    print("Unknown msg")

回答

2 Reinderien Oct 14 2020 at 00:41

@vnpが言ったこと。基本的に、

  • input使用stdin;
  • stdin Windowsを使用していない限り、ファイルハンドルとして解釈できます。
  • select そのようなハンドルでデータが利用可能になるのを待つことができます。

このトピックには、次のような多くのインターネットヘルプがあります。 https://stackoverflow.com/a/3471853/313768; そこで解決策を引用するには:

import sys 
from select import select

timeout = 10 
print "Enter something:", 
rlist, _, _ = select([sys.stdin], [], [], timeout) 
if rlist:
    s = sys.stdin.readline()
    print s 
else:
    print "No input. Moving on..."