Python实现定时精度可调节的定时器

yipeiwu_com6年前Python基础

本文实例为大家分享了Python实现定时精度可调节的定时器,供大家参考,具体内容如下

# -* coding: utf-8 -*- 
 
import sys 
import os 
import getopt 
import threading 
import time 
 
def Usage(): 
  usage_str = '''''说明: 
  \t定时器 
  \timer.py -h 显示本帮助信息,也可以使用--help选项 
  \timer.py -d num 指定一个延时时间(以毫秒为单位) 
  \t          也可以使用--duration=num选项 
  ''' 
  print(usage_str) 
   
   
def args_proc(argv): 
  '''''处理命令行参数''' 
  try: 
    opts, args = getopt.getopt(sys.argv[1:], 'hd:', ['help', 'duration=']) 
  except getopt.GetoptError as err: 
    print('错误!请为脚本指定正确的命令行参数。\n') 
    Usage() 
    sys.exit(255) 
     
  if len(opts) < 1: 
    print('使用提示:缺少必须的参数。') 
    Usage() 
    sys.exit(255) 
     
  usr_argvs = {} 
  for op, value in opts: 
    if op in ('-h', '--help'): 
      Usage() 
      sys.exit(1) 
    elif op in ('-d', '--duration'): 
      if int(value) <= 0: 
        print('错误!指定的参数值%s无效。\n' % (value)) 
        Usage() 
        sys.exit(2) 
      else: 
        usr_argvs['-d'] = int(value) 
    else: 
      print('unhandled option') 
      sys.exit(3) 
 
  return usr_argvs 
   
def timer_proc(interval_in_millisecond): 
  loop_interval = 10   # 定时精度,也是循环间隔时间(毫秒),也是输出信息刷新间隔时间,它不能大于指定的最大延时时间,否则可能导致无任何输出 
  t = interval_in_millisecond / 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') 
    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') 
  print() 
   
# 应用程序入口 
if __name__ == '__main__': 
  usr_argvs = {} 
  usr_argvs = args_proc(sys.argv) 
  for argv in usr_argvs: 
    if argv in ( '-d', '--duration'): 
      timer_proc(usr_argvs[argv]) 
    else: 
      continue 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

解决使用PyCharm时无法启动控制台的问题

问题: 使用PyCharm时无法启动控制台? 今天打开PyCharm时突然无法启动控制台,IPython和Python本身都无法使用 解决: 很有可能你安装了较高版本的ipython...

深入解析Python中的集合类型操作符

(1)标准类型操作符(所有的集合类型) 成员关系 (in, not in)         就序列而言,Python...

python通过索引遍历列表的方法

本文实例讲述了python通过索引遍历列表的方法。分享给大家供大家参考。具体如下: python中我们可以通过for循环来遍历列表: colours = ["red","green"...

Python中property函数用法实例分析

本文实例讲述了Python中property函数用法。分享给大家供大家参考,具体如下: 通常我们在访问和赋值属性的时候,都是在直接和类(实例的)的__dict__打交道,或者跟数据描述符...

Windows下安装python2.7及科学计算套装

Windows下安装python2.7及科学计算套装

安装环境及说明 操作系统:64位win7 以下所有安装包已经被我打包至网盘,请移步到 http://www.colafile.com/file/4591550进行下载 因为在64位win...