Python Cookbook学习记录 ch3_10/11_2013/10/30

3.10 反复执行某个命令

使用time.sleep方法,以60秒为周期,通过os.system方法来执行命令。

sys.argv[0]获取的第一个参数是脚本名称,之后是参数,当参数小于1或者大于2说明参数的个数不对。

当参数个数为1时,执行第一种情况,周期默认为60秒,当参数个数为2时,执行第二种情况,时间周期通过脚本自己设定参数

import time, os, sys
def main(cmd, inc=60):
    while True:
        os.system(cmd)
        time.sleep(inc)
if __name__ == '__main__' :
    numargs = len(sys.argv) - 1
    if numargs < 1 or numargs > 2:
        print "usage: " + sys.argv[0] + " command [seconds_delay]"
        sys.exit(1)
    cmd = sys.argv[1]
    if numargs < 3:
        main(cmd)
    else:
        inc = int(sys.argv[2])
        main(cmd, inc)

3.11 定时执行命令

需要在某个确定的时候执行某个命令

使用sched模块的方法,首先需要创建一个scheduler的实例,只有通过实例的enter方法,即现在开始的时间或者使用enterabs方法,即使用绝对时间

这两个方法的帮助文档如下。级第一个参数为时间或者时延,第二个参数为优先级,第三个参数为供调用的函数,第四个参数为容纳前面函数调用的元组

     |  enter(self, delay, priority, action, argument)
     |      A variant that specifies the time as a relative time.
     |      
     |      This is actually the more commonly used interface.
     |  
     |  enterabs(self, time, priority, action, argument)
     |      Enter a new event in the queue at an absolute time.
     |      
     |      Returns an ID for the event which can be used to remove it,
     |      if necessary.

文中的代码如下,可以看到perform_command每次执行完后都会过inc秒后再次运行自己,这样子就被周期性的调用

import time, os, sys, sched
schedule = sched.scheduler(time.time, time.sleep)
def perform_command(cmd, inc):
    schedule.enter(inc, 0, perform_command, (cmd, inc)) # re-scheduler
    os.system(cmd)
def main(cmd, inc=60):
    schedule.enter(0, 0, perform_command, (cmd, inc))   # 0==right now
    schedule.run()
if __name__ == '__main__' :
    numargs = len(sys.argv) - 1
    if numargs < 1 or numargs > 2:
        print "usage: " + sys.argv[0] + " command [seconds_delay]"
        sys.exit(1)
    cmd = sys.argv[1]
    if numargs < 3:
        main(cmd)
    else:
        inc = int(sys.argv[2])
        main(cmd, inc)

 

posted on 2013-10-30 22:56  七海之风  阅读(165)  评论(0)    收藏  举报

导航