python 定时器用法 + 获取脚本所在绝对路径 + 定义日志格式 的测试代码
如果用 python 写好一个有定时器的脚本后, 如果脚本里还读了配置文件, 那么配置文件路径如果写死的话, 有一天要换了存放目录的话, 需要修改脚本的配置文件路径, 而且每次都要到脚本所在路径用 nohup 启动到后台很麻烦.
用 os.path.split(os.path.realpath(sys.argv[0]))[0] 来获取文件所在的绝对路径, 配置文件同样扔到和它同级, 这样就可以在任意地方启动, 一劳永逸~~~
此用法站在运维常用的角度思考, 放到任意路径在任何路径下都能调用, 解决路径不对问题.
python 脚本
- vim test_parameters.py
- #!/usr/bin/python
- # -*- coding:utf-8 -*-
- #########################
- import threading
- import logging
- import time
- import os,sys
- # 获取脚本所在路径
- location_path = os.path.split(os.path.realpath(sys.argv[0]))[0]
- # 定义日志格式
- logging.basicConfig(level=logging.DEBUG,
- format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s -------> %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
- filename='%s/logs/test_timer.log'%location_path, # 将日志打印到脚本所在路径下
- filemode='a')
- # 测试带参数的函数用法, 函数的参数必须用 [ ]
- def Test_Parameters(path):
- logging.info("这是本脚本所在路径: %s" % path)
- global timer
- timer = threading.Timer(60, Test_Parameters,[path]) #每 60 秒运行一次
- timer.start()
- # 不带参数的用法
- def Test_Nop():
- logging.info("Hello world...")
- global timer
- timer = threading.Timer(3.0,Test_Nop) #每三秒运行一次
- timer.start()
- if __name__ == "__main__":
- timer = threading.Timer(10,Test_Parameters,[location_path])
- timer.start()
- #测试 Test_Nop()
- #timer = threading.Timer(10,Test_Nop) # 10 秒后开始运行 Test_Nop()
- #timer.start()
shell 脚本启动停止
- #!/bin/bash
- pypath=$(cd "$(dirname"$0")"; pwd) # 获取脚本所在路径
- PID=`ps -ef | grep test_parameters | awk '!/grep/{print $2}'`
- case $1 in
- start)
nohup python $pypath/test_parameters.py &
- ;;
- stop)
- kill -9 $PID
- ;;
- restart)
- kill -9 $PID
- sleep 3
nohup python $pypath/test_parameters.py &
- ;;
- *)
- echo "$0 [ start | stop | restart ]"
- exit 1
- ;;
- esac
来源: http://www.bubuko.com/infodetail-2575584.html