本帖最后由 Gin_Q 于 2020-8-6 11:24 编辑
- #coding=utf-8
-
- from multiprocessing import Process,Queue
- import time
- import os, sys
-
- q = Queue()
- sec = 5
- choose = 0
-
- def input_wiat(q, fn):
- sys.stdin = os.fdopen(fn)
- while True:
- try:
- time.sleep(1)
- n = int(input('默请在5秒内输入一个整数\n默认为0\n请输入:'))
- q.put(n)
- break
- except ValueError:
- continue
- time.sleep(10)
-
- if __name__ == '__main__':
- fn = sys.stdin.fileno()
- p = Process(target=input_wiat, args=(q, fn))
- p.start()
- while sec:
- if not q.empty():
- choose = q.get()
- break
- time.sleep(1)
- sec -= 1
- p.terminate()
- print('choose = {}'.format(choose))
- print(input('s'))
复制代码 class:- #coding=utf-8
- '''
- @ BY Cool_Breeze
- @ 2020/08/06
- @ 多线程接受用户输入
- @ Rev 01
- '''
-
-
- from threading import Thread
- from queue import Queue
- import time
- import os, sys
-
- class input_wiat:
- '''
- @ string 提示字符串
- @ sec 等待时间 time.slee()
- @ fileno IO文件描述
- '''
- def __init__(self, string, sec, fileno):
- self.string = string
- self.sec = sec
- self.fileno = fileno
- self.q = Queue()
- self.qb = Queue()
-
- def start(self):
- def f(q):
- while True:
- try:
- sys.stdin = os.fdopen(self.fileno)
- n = int(input(self.string))
- q.put(n)
- break
- except ValueError:
- continue
- p = Thread(target=f, args=(self.q,))
- p.setDaemon(True)
- p.start()
-
- def wait(self):
- def f(qb):
- while True:
- time.sleep(self.sec)
- qb.put(True)
-
- p = Thread(target=f, args=(self.qb,))
- p.setDaemon(True)
- p.start()
-
- def result(self):
- self.wait()
- self.start()
- while True:
- if not self.q.empty():
- return self.q.get()
- if not self.qb.empty():
- return 0 #deflaut
-
-
- if __name__ == '__main__':
- t = input_wiat('请输入:\n',5 , sys.stdin.fileno())
- print('返回结果 :{}'.format(t.result()))
复制代码
|