若是用python写好一个有定时器的脚本后,若是脚本里还读了配置文件,那么配置文件路径若是写死的话,有一天要换了存放目录的话,须要修改脚本的配置文件路径,并且每次都要到脚本所在路径用 nohup 启动到后台很麻烦。
用 os.path.split(os.path.realpath(sys.argv[0]))[0] 来获取文件所在的绝对路径,配置文件一样扔到和它同级,这样就能够在任意地方启动,一劳永逸~~~python
此用法站在运维经常使用的角度思考,放到任意路径在任何路径下都能调用,解决路径不对问题。shell
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()
#!/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