若是用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