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]) # 10秒後開始運行
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