crontab中部署Python腳本注意事項


有時候手工執行Python腳本跑的好好的,但是部署到Linux的crontab中后,就會遇到一些問題,最近終於有空整理一下這方面的內容,其實也是自己也踩了一些別人踩過的坑!這里僅僅列舉個人遇到的一些小問題,經驗和精力問題,不能面面俱到,僅總結一下自己遇到的這些問題。

 

 

環境變量問題

 

cron中的環境變量和系統的環境變量是不一樣的,我們可以通過設置定時腳本將cron中的環境變量打印出來,然后一對比,你就能發現差異

 

       * * * * * env > /tmp/env.txt

 

如果你Python腳本中要獲取環境變量的話,那么部署到Crontab作業后就要小心了,很有可能手工運行腳本是正常的,但是部署到Crontab后運行就不正常了,如下所示,我們構造這樣一個測試腳本crontab_env_test.py

 

#!/usr/bin/python
# -*- coding: utf-8 -*-
 
import logging
import os.path
import os
import base64
 
 
 
# 第一步,創建一個logger
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)  # Log等級開關
# 第二步,創建一個handler,用於寫入日志文件
log_path = '/home/konglb/logs/'
log_name = log_path + 'kerry_test.log'
logfile = log_name
file_handler = logging.FileHandler(logfile, mode='a+')
file_handler.setLevel(logging.ERROR)  # 輸出到file的log等級的開關
# 第三步,定義handler的輸出格式
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
file_handler.setFormatter(formatter)
# 第四步,將handler添加到logger里面
logger.addHandler(file_handler)
# 如果需要同時需要在終端上輸出,定義一個streamHandler
print_handler = logging.StreamHandler()  # 往屏幕上輸出
print_handler.setFormatter(formatter)  # 設置屏幕上顯示的格式
logger.addHandler(print_handler)
 
 
db_user=os.environ.get('my_env')
print(db_user)
logger.error(db_user)

 

如下所示,手工執行該腳本,就會往/home/konglb/logs/kerry_test.log中寫入環境變量my_env的值(/etc/profile中設置了export my_env=kerry )

 

# /usr/local/bin/python3.6 /home/konglb/python/crontab_env_test.py

kerry

2019-08-20 20:20:18,293 - crontab_env_test.py[line:30] - ERROR: kerry

 

然后我們配置crontab后,如下所示,通過刷新日志觀察其獲取環境變量my_env的值

 

# crontab -l

*/1 * * * *  /usr/local/bin/python3.6 /home/konglb/python/crontab_env_test.py

 

如下截圖所示,你會看到在Crontab中運行的Python腳本根本沒有獲取到環境變量my_env的值

 

# tail -60f kerry_test.log 
2019-08-20 20:20:18,293 - crontab_env_test.py[line:30] - ERROR: kerry
2019-08-20 20:22:02,337 - crontab_env_test.py[line:30] - ERROR: None
2019-08-20 20:23:01,533 - crontab_env_test.py[line:30] - ERROR: None
2019-08-20 20:24:01,682 - crontab_env_test.py[line:30] - ERROR: None
2019-08-20 20:25:01,832 - crontab_env_test.py[line:30] - ERROR: None
2019-08-20 20:26:01,103 - crontab_env_test.py[line:30] - ERROR: None
2019-08-20 20:27:01,243 - crontab_env_test.py[line:30] - ERROR: None
2019-08-20 20:28:01,397 - crontab_env_test.py[line:30] - ERROR: None
2019-08-20 20:29:01,543 - crontab_env_test.py[line:30] - ERROR: None
2019-08-20 20:30:01,680 - crontab_env_test.py[line:30] - ERROR: None
2019-08-20 20:31:01,998 - crontab_env_test.py[line:30] - ERROR: None
2019-08-20 20:32:01,223 - crontab_env_test.py[line:30] - ERROR: None
2019-08-20 20:33:01,369 - crontab_env_test.py[line:30] - ERROR: Non

 

那么要如何解決這個問題呢,如下所示,在執行Python腳本時,獲取/etc/profile中的系統變量(不同平台或不同環境有所區別)

 

*/1 * * * * source /etc/profile && /usr/local/bin/python3.6 /home/konglb/python/crontab_env_test.py

 

clip_image001

 

 

還有一種方案,就是使用shell包裹Python腳本,如下所示:

 

# more kerry.sh 
 
#!/bin/bash
 
source /etc/profile
 
/usr/local/bin/python3.6 /home/konglb/python/crontab_env_test.py

 

*/1 * * * *    /home/konglb/python/kerry.sh

 

 

相對路徑問題

 

把上面的腳本修改一下,使用相對路徑,如下所示,然后crontab作業運行時就會報錯

 

#!/usr/bin/python
# -*- coding: utf-8 -*-
 
import logging
import os.path
import os
import base64
 
 
 
# 第一步,創建一個logger
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)  # Log等級開關
# 第二步,創建一個handler,用於寫入日志文件
#log_path = '/home/konglb/logs/'
log_path = os.path.dirname(os.getcwd()) + '/logs/'
log_name = log_path + 'kerry_test.log'
logfile = log_name
file_handler = logging.FileHandler(logfile, mode='a+')
file_handler.setLevel(logging.ERROR)  # 輸出到file的log等級的開關
# 第三步,定義handler的輸出格式
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
file_handler.setFormatter(formatter)
# 第四步,將handler添加到logger里面
logger.addHandler(file_handler)
# 如果需要同時需要在終端上輸出,定義一個streamHandler
print_handler = logging.StreamHandler()  # 往屏幕上輸出
print_handler.setFormatter(formatter)  # 設置屏幕上顯示的格式
logger.addHandler(print_handler)
 
 
db_user=os.environ.get('my_env')
print(db_user)
logger.error(db_user)

 

其實切換到其它路徑后,手工執行該腳本也會報錯誤,因為相對路徑的設置,導致一些邏輯錯誤出現,如下所示,所以如果要部署為Crontab作業的Python腳本,最好使用絕對路徑,避免出現這個問題。

 

# pwd
/root
# /usr/local/bin/python3.6 /home/konglb/python/crontab_env_test.py
Traceback (most recent call last):
  File "/home/konglb/python/crontab_env_test.py", line 19, in <module>
    file_handler = logging.FileHandler(logfile, mode='a+')
  File "/usr/local/lib/python3.6/logging/__init__.py", line 1031, in __init__
    StreamHandler.__init__(self, self._open())
  File "/usr/local/lib/python3.6/logging/__init__.py", line 1060, in _open
    return open(self.baseFilename, self.mode, encoding=self.encoding)
FileNotFoundError: [Errno 2] No such file or directory: '//logs/kerry_test.log'

 

 

 

另外,像密碼過期導致crontab不執行作業(Linux賬號密碼過期會導致crontab作業不能執行)這樣的案例也遇到過,不過這個與Python腳本無關系,如果遇到相關問題,可以從Why-Cronjob-Not-Work這篇文章介紹的這幾個方面去思考、分析判斷。

 

 

參考資料

 

 https://www.tony-yin.site/2018/10/29/Why-Crontab-Not-Work/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM