chzhiyi / -KnowledgeShare

6 stars 1 forks source link

20190416 - 倒计时代码 - qiaosong #53

Open chzhiyi opened 5 years ago

chzhiyi commented 5 years ago

参考网址:https://www.jb51.net/article/127315.htm

倒计时代码

import sys
import getopt
import time

def usage():
    """帮助信息"""
    usage_str = '''
NAME
\t timing\n
SYNOPSIS
\t python3 timing.py [OPTION]...\n
OPTIONS
\t -h, --help
\t\t display this help and exit\n
\t -d, --duration=N
\t\t specify N seconds to countdown time; use -d N or --duration=N
    '''
    print(usage_str)

def args_proc():
    """处理命令行参数"""
    argvs = {}

    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hd:', ['help', 'duration='])  ## 最主要的一句
    except getopt.GetoptError as err:
        print('ERROR: 请为脚本指定正确的命令行参数, 异常信息为: ', err)
        usage()
        sys.exit(255)

    if len(opts) < 1:
        print('TIPS:缺少必须的参数.')
        usage()
        sys.exit(255)

    for op, value in opts:
        if op in ('-h', '--help'):
            usage()
            sys.exit(1)
        elif op in ('-d', '--duration'):
            if int(value) <= 0:
                print('Error!%s is not an Integer, bigger than 0.\n' % (value))
                usage()
                sys.exit(2)
            else:
                argvs['-d'] = int(value)
        else:
            print('unsupported options: ', op)
            sys.exit(3)
    return argvs

def timer_proc(interval_in_second):
    loop_interval = 100  # 定时精度,也是循环间隔时间(毫秒), 每100ms刷新下时间
    t = interval_in_second * 1000 / loop_interval
    while t >= 0:
        min = (t * loop_interval) / 1000 / 60
        sec = (t * loop_interval) / 1000 % 60
        millisecond = (t * loop_interval) % 1000
        print('\rThe remaining time: %02d:%02d.%03d' % (min, sec, millisecond), end='\t\t')  ## %02d,表示左边补0;\r,将光标的位置回退到本行的开头位置
        time.sleep(loop_interval / 1000)
        t -= 1
    if millisecond != 0:
        millisecond = 0
        print('\rThe remaining time: %02d:%02d.%03d' % (min, sec, millisecond), end='\t\t')

if __name__ == '__main__':
    usr_argvs = args_proc()
    for argv in usr_argvs:
        if argv in ('-d', '--duration'):
            timer_proc(usr_argvs[argv])
        else:
            continue

重点关注

opts, args = getopt.getopt(sys.argv[1:], 'hd:', ['help', 'duration=']) sys.exit(number)

opts, args = getopt.getopt(sys.argv[1:], 'hd:', ['help', 'duration='])

# status为空或为None,默认为0-成功;为integer,作为系统退出状体码;为其它任意对象,则为1-失败。

def exit(status=None): # real signature unknown; restored from __doc__
    """
    exit([status])

    Exit the interpreter by raising SystemExit(status).
    If the status is omitted or None, it defaults to zero (i.e., success).
    If the status is an integer, it will be used as the system exit status.
    If it is another kind of object, it will be printed and the system
    exit status will be one (i.e., failure).
    """
    pass

sys.exit(number)

def getopt(args, shortopts, longopts = []):
    """getopt(args, options[, long_options]) -> opts, args

    Parses command line options and parameter list.  args is the
    argument list to be parsed, without the leading reference to the
    running program.  Typically, this means "sys.argv[1:]".  shortopts
    is the string of option letters that the script wants to
    recognize, with options that require an argument followed by a
    colon (i.e., the same format that Unix getopt() uses).  If
    specified, longopts is a list of strings with the names of the
    long options which should be supported.  The leading '--'
    characters should not be included in the option name.  Options
    which require an argument should be followed by an equal sign
    ('=').

    The return value consists of two elements: the first is a list of
    (option, value) pairs; the second is the list of program arguments
    left after the option list was stripped (this is a trailing slice
    of the first argument).  Each option-and-value pair returned has
    the option as its first element, prefixed with a hyphen (e.g.,
    '-x'), and the option argument as its second element, or an empty
    string if the option has no argument.  The options occur in the
    list in the same order in which they were found, thus allowing
    multiple occurrences.  Long and short options may be mixed.

    """

    opts = []
    if type(longopts) == type(""):
        longopts = [longopts]
    else:
        longopts = list(longopts)
    while args and args[0].startswith('-') and args[0] != '-':
        if args[0] == '--':
            args = args[1:]
            break
        if args[0].startswith('--'):
            opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
        else:
            opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])

    return opts, args