鱼C论坛

 找回密码
 立即注册
查看: 3564|回复: 13

请问有没有办法让python在input的时候执行命令?

[复制链接]
发表于 2020-10-24 21:34:19 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
我想写出一个程序,让用户在10秒钟之内输入答案,如果10秒钟之内用户没有输入,则继续运行一些其他程序。请问有办法这样写吗?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-10-24 21:39:23 | 显示全部楼层
后面加上time.sleep(10)然后if判断input里有没有输入值,
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-10-24 22:01:23 | 显示全部楼层
v.ki 发表于 2020-10-24 21:39
后面加上time.sleep(10)然后if判断input里有没有输入值,

emmm没明白。请问您可不可以写一行代码(形象一点)呢?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-10-24 22:34:42 | 显示全部楼层
v.ki 发表于 2020-10-24 21:39
后面加上time.sleep(10)然后if判断input里有没有输入值,

没有任何用,这个得多线程
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-10-24 22:35:53 | 显示全部楼层
永恒的蓝色梦想 发表于 2020-10-24 22:34
没有任何用,这个得多线程

那请问你知道要怎么多线程吗?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-10-24 22:39:09 | 显示全部楼层
本帖最后由 聂嘉辉 于 2020-10-24 22:44 编辑



我知道:
  1. from threading import Thread
  2. import time
  3. import sys, msvcrt

  4. def input_value(*n):
  5.     global value
  6.     chars = []
  7.     print(''.join(n), end='')
  8.     while True:
  9.         newChar = msvcrt.getch()
  10.         if newChar in b'\r\n': # 如果是换行,则输入结束
  11.             break
  12.         elif newChar == b'\b': # 如果是退格,则删除末尾一位
  13.             if chars:
  14.                 del chars[-1]
  15.                 sys.stdout.write('\b')
  16.     value = ''.join(chars)

  17. value = ''
  18. th = Thread(target = input_value, args = 'input a value:')
  19. th.start()
  20. th.join(timeout=10)   #设置超时时间
  21. print(value)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-10-24 22:48:59 | 显示全部楼层
聂嘉辉 发表于 2020-10-24 22:39
记得最佳答案

我知道:

哪有这么麻烦……
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-10-24 22:50:27 | 显示全部楼层

你有本事你做呀!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-10-24 22:52:24 | 显示全部楼层
永恒的蓝色梦想 发表于 2020-10-24 22:34
没有任何用,这个得多线程

我的错,没认真看题目
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-10-24 22:53:21 | 显示全部楼层
就是不要用input会导致阻塞
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-10-25 12:40:45 | 显示全部楼层
本帖最后由 Stubborn 于 2020-10-25 12:42 编辑
  1. @func_set_timeout(10)
  2. def askChoice():
  3.     return input('yes or no:')

  4. try:
  5.     s = askChoice()
  6. except FunctionTimedOut as e:
  7.     s = 'f'
  8. print(s)
复制代码

  1. import copy
  2. import ctypes
  3. import os
  4. import sys
  5. import threading
  6. import types
  7. from functools import wraps

  8. RETRY_SAME_TIMEOUT = 'RETRY_SAME_TIMEOUT'


  9. class FunctionTimedOut(BaseException):

  10.     def __init__(self, msg='', timedOutAfter=None, timedOutFunction=None, timedOutArgs=None, timedOutKwargs=None):

  11.         self.timedOutAfter = timedOutAfter

  12.         self.timedOutFunction = timedOutFunction
  13.         self.timedOutArgs = timedOutArgs
  14.         self.timedOutKwargs = timedOutKwargs

  15.         if not msg:
  16.             msg = self.getMsg()

  17.         BaseException.__init__(self, msg)

  18.         self.msg = msg

  19.     def getMsg(self):
  20.         if self.timedOutFunction is not None:
  21.             timedOutFuncName = self.timedOutFunction.__name__
  22.         else:
  23.             timedOutFuncName = 'Unknown Function'
  24.         if self.timedOutAfter is not None:
  25.             timedOutAfterStr = "%f" % (self.timedOutAfter,)
  26.         else:
  27.             timedOutAfterStr = "Unknown"

  28.         return 'Function %s (args=%s) (kwargs=%s) timed out after %s seconds.\n' % (
  29.             timedOutFuncName, repr(self.timedOutArgs), repr(self.timedOutKwargs), timedOutAfterStr)

  30.     def retry(self, timeout=RETRY_SAME_TIMEOUT):
  31.         if timeout is None:
  32.             return self.timedOutFunction(*(self.timedOutArgs), **self.timedOutKwargs)

  33.         if timeout == RETRY_SAME_TIMEOUT:
  34.             timeout = self.timedOutAfter

  35.         return func_timeout(timeout, self.timedOutFunction, args=self.timedOutArgs, kwargs=self.timedOutKwargs)


  36. class StoppableThread(threading.Thread):

  37.     def _stopThread(self, exception, raiseEvery=2.0):
  38.         if self.is_alive() is False:
  39.             return True

  40.         self._stderr = open(os.devnull, 'w')
  41.         joinThread = JoinThread(self, exception, repeatEvery=raiseEvery)
  42.         joinThread._stderr = self._stderr
  43.         joinThread.start()
  44.         joinThread._stderr = self._stderr

  45.     def stop(self, exception, raiseEvery=2.0):
  46.         return self._stopThread(exception, raiseEvery)


  47. class JoinThread(threading.Thread):

  48.     def __init__(self, otherThread, exception, repeatEvery=2.0):
  49.         threading.Thread.__init__(self)
  50.         self.otherThread = otherThread
  51.         self.exception = exception
  52.         self.repeatEvery = repeatEvery
  53.         self.daemon = True

  54.     def run(self):

  55.         self.otherThread._Thread__stderr = self._stderr
  56.         if hasattr(self.otherThread, '_Thread__stop'):
  57.             self.otherThread._Thread__stop()
  58.         while self.otherThread.is_alive():
  59.             ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(self.otherThread.ident),
  60.                                                        ctypes.py_object(self.exception))
  61.             self.otherThread.join(self.repeatEvery)

  62.         try:
  63.             self._stderr.close()
  64.         except:
  65.             pass


  66. def func_timeout(timeout, func, args=(), kwargs=None):
  67.     def raise_exception(exception):
  68.         raise exception[0] from None

  69.     if not kwargs:
  70.         kwargs = {}
  71.     if not args:
  72.         args = ()

  73.     ret = []
  74.     exception = []
  75.     isStopped = False

  76.     def funcwrap(args2, kwargs2):
  77.         try:
  78.             ret.append(func(*args2, **kwargs2))
  79.         except FunctionTimedOut:
  80.             pass
  81.         except Exception as e:
  82.             exc_info = sys.exc_info()
  83.             if isStopped is False:
  84.                 e.__traceback__ = exc_info[2].tb_next
  85.                 exception.append(e)

  86.     thread = StoppableThread(target=funcwrap, args=(args, kwargs))
  87.     thread.daemon = True

  88.     thread.start()
  89.     thread.join(timeout)

  90.     stopException = None
  91.     if thread.is_alive():
  92.         isStopped = True

  93.         class FunctionTimedOutTempType(FunctionTimedOut):
  94.             def __init__(self):
  95.                 return FunctionTimedOut.__init__(self, '', timeout, func, args, kwargs)

  96.         FunctionTimedOutTemp = type(
  97.             'FunctionTimedOut' + str(hash("%d_%d_%d_%d" % (id(timeout), id(func), id(args), id(kwargs)))),
  98.             FunctionTimedOutTempType.__bases__, dict(FunctionTimedOutTempType.__dict__))

  99.         stopException = FunctionTimedOutTemp
  100.         thread._stopThread(stopException)
  101.         thread.join(min(.1, timeout / 50.0))
  102.         raise FunctionTimedOut('', timeout, func, args, kwargs)
  103.     else:
  104.         thread.join(.5)

  105.     if exception:
  106.         raise_exception(exception)

  107.     if ret:
  108.         return ret[0]


  109. def func_set_timeout(timeout, allowOverride=False):
  110.     defaultTimeout = copy.copy(timeout)

  111.     isTimeoutAFunction = bool(issubclass(timeout.__class__, (
  112.         types.FunctionType, types.MethodType, types.LambdaType, types.BuiltinFunctionType, types.BuiltinMethodType)))

  113.     if not isTimeoutAFunction:
  114.         if not issubclass(timeout.__class__, (float, int)):
  115.             try:
  116.                 timeout = float(timeout)
  117.             except:
  118.                 raise ValueError(
  119.                     '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.' % (
  120.                         timeout.__class__.__name__,))

  121.     if not allowOverride and not isTimeoutAFunction:
  122.         def _function_decorator(func):
  123.             return wraps(func)(lambda *args, **kwargs: func_timeout(defaultTimeout, func, args=args, kwargs=kwargs))

  124.         return _function_decorator

  125.     if not isTimeoutAFunction:
  126.         def _function_decorator(func):
  127.             def _function_wrapper(*args, **kwargs):
  128.                 if 'forceTimeout' in kwargs:
  129.                     useTimeout = kwargs.pop('forceTimeout')
  130.                 else:
  131.                     useTimeout = defaultTimeout

  132.                 return func_timeout(useTimeout, func, args=args, kwargs=kwargs)

  133.             return wraps(func)(_function_wrapper)

  134.         return _function_decorator

  135.     timeoutFunction = timeout

  136.     if allowOverride:
  137.         def _function_decorator(func):
  138.             def _function_wrapper(*args, **kwargs):
  139.                 if 'forceTimeout' in kwargs:
  140.                     useTimeout = kwargs.pop('forceTimeout')
  141.                 else:
  142.                     useTimeout = timeoutFunction(*args, **kwargs)

  143.                 return func_timeout(useTimeout, func, args=args, kwargs=kwargs)

  144.             return wraps(func)(_function_wrapper)

  145.         return _function_decorator

  146.     def _function_decorator(func):
  147.         def _function_wrapper(*args, **kwargs):
  148.             useTimeout = timeoutFunction(*args, **kwargs)

  149.             return func_timeout(useTimeout, func, args=args, kwargs=kwargs)

  150.         return wraps(func)(_function_wrapper)

  151.     return _function_decorator
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-10-25 16:11:14 | 显示全部楼层


你这也太太太太太夸张了吧
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-10-25 18:15:36 | 显示全部楼层
叼辣条闯世界 发表于 2020-10-25 16:11
你这也太太太太太夸张了吧

用起来 很简单的
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-10-25 22:31:18 | 显示全部楼层
  1. import time
  2. import threading

  3. def A():
  4.     a=input("请输入任意向输入的文字,否则在10秒后会执行其他程序!,输入:")
  5.     print(a)

  6. def B():
  7.     for i in range(5):
  8.         print("---跳转完成---")


  9. def main():
  10.     t1=threading.Thread(target=A)
  11.     t2=threading.Thread(target=B)
  12.     t1.start()
  13.     time.sleep(10)
  14.     t2.start()
复制代码

不知道是不是你想要的答案
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-18 04:23

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表