我想從cron運行Python腳本。我使用crontab作爲用戶而不是root來運行命令。我的Python腳本在頂部#! /usr/bin/env python
有shebang,我做了chmod +x
它使腳本可執行。Python腳本沒有在cron中運行
該腳本在從shell運行但不使用crontab時不起作用。我沒有檢查/var/log/cron
文件,看到腳本運行,但從stdout
或stderr
打印任何地方都沒有。
最後,我做了一個小腳本,它打印日期和一個字符串,並稱每分鐘都有效,但這個腳本沒有。我不知道爲什麼我收到這些變化的結果...
這是我在crontab
SHELL=/bin/bash
#min #hour day-of-month month day-of-week command
#-------------------------------------------------------------------------
*/5 * * * * /path/to/script/script.py
這裏條目我的腳本的源代碼不會從crontab中運行,但會從運行它在被調用的時候就像是這樣的./script.py
。該腳本是可執行的我用chmod +x
命令後,就可以了,順便說一句...:
#! /usr/bin/env python
#create a file and write to it
import time
def create_and_write():
with open("py-write-out.out", "a+") as w:
w.write("writing to file. hello from python. :D\n")
w.write("the time is: " + str(time.asctime()) + "\n")
w.write("--------------------------------\n")
def main():
create_and_write()
if __name__ == "__main__":
main()
編輯 我想通了什麼事情錯了。我需要將絕對文件路徑放在腳本中,否則它會寫入我沒有計劃的某個目錄。
請包括相關的代碼 - 這將幫助我們回答。 – l0b0 2014-09-25 23:01:48
在可能影響腳本的shell環境之間經常會有其他差異:不同的'PYTHONPATH'是一種可能性。您可能希望在'cron'下運行一個腳本,該腳本只是打印其環境,並將其與基於shell的手動執行的期望進行比較。 – 2014-09-25 23:42:56
你重定向stdout和stderr嗎?你期望看到它們出現在哪裏? – cdarke 2014-09-26 04:59:47