【python学习】Python限制input输入时间并设置超时后的default值

在工作中使用python的input函数,可以使脚本具有更强的灵活性,但一旦用的脚本多了,有时候就会忘记某些脚本需要手动输入信息,启动脚本后以为已经开始进行了,实际情况是:没有输入信息,导致脚本一直卡在输入状态。

为了解决这种情况的发生,我们可以在输入超时情况下设置一个default值,让脚本在经过多少时间之后,会get默认值进行下一步工作,而这个默认值我们可以设置为常用的情况,这样就不容易浪费时间(经常想让一个脚本跑一晚上,下班前就把脚本提上了,结果第二天早上一来发现,脚本还在input状态装死呢。。。一口老血。。。)

直接上代码:(内容有点啰嗦,大家看需求参考)

import os
from threading import Timer

def do_sth(in_sth):
    # Judge if in_sth is a number
    if type(in_sth) == type(1): # Any int number
        # do_sth (just an example)
        print("\n--- I think that you are %d years old! \n" %in_sth)
    # Judge if in_sth is a string
    elif type(in_sth) == type("a"): # Any string
        # do_sth (just an example)
        print("\n--- You know what, it is just a %s! \n" %in_sth)
    return

def input_msg(msg="", dft="18"):
    if(len(msg)>0):
        in_sth = msg
    else:
        print("\n--- You input nothing, the default message is %s!\n" %dft)
        in_sth = dft
    
    # Judge if input string is a number
    if in_sth.isdigit(): in_sth = int(in_sth)
    # Then do something for the input message
    do_sth(in_sth)
    # Exit
    os._exit(0)

def input_timeout(timeout=5):
    t = Timer(timeout, input_msg)
    t.start()
    msg = input("\n--- Please input a message: (Please input in %d seconds) \n" %timeout)

    if len(msg)>0:
        t.cancel()
        input_msg(msg)

# Run to test
input_timeout()

如有错误,欢迎指正,谢谢!

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值