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设计】。

相关文章

python3 读取Excel表格中的数据

需要先安装openpyxl库 通过pip命令安装: pip install openpyxl 源码如下: #!/usr/bin/python3 #-*- coding:utf-8 -...

Python Gitlab Api 使用方法

简述 公司使用gitlab 来托管代码,日常代码merge request 以及其他管理是交给测试,鉴于操作需经常打开网页,重复且繁琐,所以交给Python 管理。 官方文档 安装 pi...

使用virtualenv创建Python环境及PyQT5环境配置的方法

使用virtualenv创建Python环境及PyQT5环境配置的方法

一、写在前面   从学 Python 的第一天起,我就知道了使用 pip 命令来安装包,从学习爬虫到学习 Web 开发,安装的库越来越多,从 requests 到 lxml,从 Djan...

详解Python中的各种函数的使用

 函数是有组织的,可重复使用的代码,用于执行一个单一的,相关的动作的块。函数为应用程序和代码重用的高度提供了更好的模块。 正如我们知道的,Python的print()等许多内置...

python getopt详解及简单实例

 python getopt详解 函数原型: getopt.getopt(args, shortopts, longopts=[]) 参数解释: args:args...