请问有没有办法让python在input的时候执行命令?
我想写出一个程序,让用户在10秒钟之内输入答案,如果10秒钟之内用户没有输入,则继续运行一些其他程序。请问有办法这样写吗? 后面加上time.sleep(10)然后if判断input里有没有输入值, v.ki 发表于 2020-10-24 21:39后面加上time.sleep(10)然后if判断input里有没有输入值,
emmm没明白。请问您可不可以写一行代码(形象一点)呢? v.ki 发表于 2020-10-24 21:39
后面加上time.sleep(10)然后if判断input里有没有输入值,
没有任何用,这个得多线程{:10_277:} 永恒的蓝色梦想 发表于 2020-10-24 22:34
没有任何用,这个得多线程
那请问你知道要怎么多线程吗? 本帖最后由 聂嘉辉 于 2020-10-24 22:44 编辑
记得最佳答案
我知道:
from threading import Thread
import time
import sys, msvcrt
def input_value(*n):
global value
chars = []
print(''.join(n), end='')
while True:
newChar = msvcrt.getch()
if newChar in b'\r\n': # 如果是换行,则输入结束
break
elif newChar == b'\b': # 如果是退格,则删除末尾一位
if chars:
del chars[-1]
sys.stdout.write('\b')
value = ''.join(chars)
value = ''
th = Thread(target = input_value, args = 'input a value:')
th.start()
th.join(timeout=10) #设置超时时间
print(value)
聂嘉辉 发表于 2020-10-24 22:39
记得最佳答案
我知道:
哪有这么麻烦…… 永恒的蓝色梦想 发表于 2020-10-24 22:48
哪有这么麻烦……
你有本事你做呀! 永恒的蓝色梦想 发表于 2020-10-24 22:34
没有任何用,这个得多线程
我的错,没认真看题目 就是不要用input会导致阻塞 本帖最后由 Stubborn 于 2020-10-25 12:42 编辑
@func_set_timeout(10)
def askChoice():
return input('yes or no:')
try:
s = askChoice()
except FunctionTimedOut as e:
s = 'f'
print(s)
import copy
import ctypes
import os
import sys
import threading
import types
from functools import wraps
RETRY_SAME_TIMEOUT = 'RETRY_SAME_TIMEOUT'
class FunctionTimedOut(BaseException):
def __init__(self, msg='', timedOutAfter=None, timedOutFunction=None, timedOutArgs=None, timedOutKwargs=None):
self.timedOutAfter = timedOutAfter
self.timedOutFunction = timedOutFunction
self.timedOutArgs = timedOutArgs
self.timedOutKwargs = timedOutKwargs
if not msg:
msg = self.getMsg()
BaseException.__init__(self, msg)
self.msg = msg
def getMsg(self):
if self.timedOutFunction is not None:
timedOutFuncName = self.timedOutFunction.__name__
else:
timedOutFuncName = 'Unknown Function'
if self.timedOutAfter is not None:
timedOutAfterStr = "%f" % (self.timedOutAfter,)
else:
timedOutAfterStr = "Unknown"
return 'Function %s (args=%s) (kwargs=%s) timed out after %s seconds.\n' % (
timedOutFuncName, repr(self.timedOutArgs), repr(self.timedOutKwargs), timedOutAfterStr)
def retry(self, timeout=RETRY_SAME_TIMEOUT):
if timeout is None:
return self.timedOutFunction(*(self.timedOutArgs), **self.timedOutKwargs)
if timeout == RETRY_SAME_TIMEOUT:
timeout = self.timedOutAfter
return func_timeout(timeout, self.timedOutFunction, args=self.timedOutArgs, kwargs=self.timedOutKwargs)
class StoppableThread(threading.Thread):
def _stopThread(self, exception, raiseEvery=2.0):
if self.is_alive() is False:
return True
self._stderr = open(os.devnull, 'w')
joinThread = JoinThread(self, exception, repeatEvery=raiseEvery)
joinThread._stderr = self._stderr
joinThread.start()
joinThread._stderr = self._stderr
def stop(self, exception, raiseEvery=2.0):
return self._stopThread(exception, raiseEvery)
class JoinThread(threading.Thread):
def __init__(self, otherThread, exception, repeatEvery=2.0):
threading.Thread.__init__(self)
self.otherThread = otherThread
self.exception = exception
self.repeatEvery = repeatEvery
self.daemon = True
def run(self):
self.otherThread._Thread__stderr = self._stderr
if hasattr(self.otherThread, '_Thread__stop'):
self.otherThread._Thread__stop()
while self.otherThread.is_alive():
ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(self.otherThread.ident),
ctypes.py_object(self.exception))
self.otherThread.join(self.repeatEvery)
try:
self._stderr.close()
except:
pass
def func_timeout(timeout, func, args=(), kwargs=None):
def raise_exception(exception):
raise exception from None
if not kwargs:
kwargs = {}
if not args:
args = ()
ret = []
exception = []
isStopped = False
def funcwrap(args2, kwargs2):
try:
ret.append(func(*args2, **kwargs2))
except FunctionTimedOut:
pass
except Exception as e:
exc_info = sys.exc_info()
if isStopped is False:
e.__traceback__ = exc_info.tb_next
exception.append(e)
thread = StoppableThread(target=funcwrap, args=(args, kwargs))
thread.daemon = True
thread.start()
thread.join(timeout)
stopException = None
if thread.is_alive():
isStopped = True
class FunctionTimedOutTempType(FunctionTimedOut):
def __init__(self):
return FunctionTimedOut.__init__(self, '', timeout, func, args, kwargs)
FunctionTimedOutTemp = type(
'FunctionTimedOut' + str(hash("%d_%d_%d_%d" % (id(timeout), id(func), id(args), id(kwargs)))),
FunctionTimedOutTempType.__bases__, dict(FunctionTimedOutTempType.__dict__))
stopException = FunctionTimedOutTemp
thread._stopThread(stopException)
thread.join(min(.1, timeout / 50.0))
raise FunctionTimedOut('', timeout, func, args, kwargs)
else:
thread.join(.5)
if exception:
raise_exception(exception)
if ret:
return ret
def func_set_timeout(timeout, allowOverride=False):
defaultTimeout = copy.copy(timeout)
isTimeoutAFunction = bool(issubclass(timeout.__class__, (
types.FunctionType, types.MethodType, types.LambdaType, types.BuiltinFunctionType, types.BuiltinMethodType)))
if not isTimeoutAFunction:
if not issubclass(timeout.__class__, (float, int)):
try:
timeout = float(timeout)
except:
raise ValueError(
'timeout argument must be a float/int for number of seconds, or a function/lambda which gets passed the function arguments and returns a calculated timeout (as float or int). Passed type: < %s > is not of any of these, and cannot be converted to a float.' % (
timeout.__class__.__name__,))
if not allowOverride and not isTimeoutAFunction:
def _function_decorator(func):
return wraps(func)(lambda *args, **kwargs: func_timeout(defaultTimeout, func, args=args, kwargs=kwargs))
return _function_decorator
if not isTimeoutAFunction:
def _function_decorator(func):
def _function_wrapper(*args, **kwargs):
if 'forceTimeout' in kwargs:
useTimeout = kwargs.pop('forceTimeout')
else:
useTimeout = defaultTimeout
return func_timeout(useTimeout, func, args=args, kwargs=kwargs)
return wraps(func)(_function_wrapper)
return _function_decorator
timeoutFunction = timeout
if allowOverride:
def _function_decorator(func):
def _function_wrapper(*args, **kwargs):
if 'forceTimeout' in kwargs:
useTimeout = kwargs.pop('forceTimeout')
else:
useTimeout = timeoutFunction(*args, **kwargs)
return func_timeout(useTimeout, func, args=args, kwargs=kwargs)
return wraps(func)(_function_wrapper)
return _function_decorator
def _function_decorator(func):
def _function_wrapper(*args, **kwargs):
useTimeout = timeoutFunction(*args, **kwargs)
return func_timeout(useTimeout, func, args=args, kwargs=kwargs)
return wraps(func)(_function_wrapper)
return _function_decorator Stubborn 发表于 2020-10-25 12:40
你这也太太太太太夸张了吧 叼辣条闯世界 发表于 2020-10-25 16:11
你这也太太太太太夸张了吧
用起来 很简单的
{:10_289:} import time
import threading
def A():
a=input("请输入任意向输入的文字,否则在10秒后会执行其他程序!,输入:")
print(a)
def B():
for i in range(5):
print("---跳转完成---")
def main():
t1=threading.Thread(target=A)
t2=threading.Thread(target=B)
t1.start()
time.sleep(10)
t2.start()
不知道是不是你想要的答案{:5_96:}
页:
[1]