我試圖在基于 linux 的作業系統中定期運行一些 python 腳本,經過快速研究,我發現crontab是一種經典的方法。我是那個命令的新手,所以我確保牢記它的常見現有建議,并且(謹慎地)我決定首先使用一個非常簡單的 python 代碼,myscript.py:
#!/usr/bin/python3
print("If you see this, your periodic code ran OK!")
' cron table' ( crontab -l) 檔案如下所示,它應該myscript.py每分鐘運行一次(我想快速測驗一下):
* * * * * /usr/bin/python3 /home/my_user_folder/Desktop/test/myscript.py
幾秒鐘過去了,腳本到達了它的第一分鐘……什么也沒發生。為了“解決它”,我嘗試了幾件事,但奇怪的是(對我來說)我意識到大多數(如果不是全部)教程和帖子都用于將訊息存盤在.txt或類似檔案中。我做了類似的事情(經過幾個小時,試驗但沒有成功),修改myscript.py為:
#!/usr/bin/python3
# NOTES:
# 1. This code is the 'final version' after several trials
# 2. Remember that I was aiming to automate anything, just
# to get familiar with `crontab`; in this case, storing
# the current time to some .txt file was enough.
import time
t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
with open('/home/my_user_folder/Desktop/test/readme.txt', 'a') as f:
f.write(current_time)
f.write('\n')
......它奏效了。我覺得有點傻,因為我意識到我最初的實作(關于代碼、環境設定、權限等)從一開始就確實是正確的,但是使用 Python 命令來“測驗”print回圈任務crontab沒有作業' ...
為什么?
uj5u.com熱心網友回復:
從 crontab 執行的命令的標準輸出不會發送到 shell 的標準輸出。(這樣做沒有多大意義;在您注銷后,cron 作業將繼續運行。)
通常crontab會(嘗試)email the output to you. This is configurable.man 5 crontab` 以獲取更多資訊。
您可以在 crontab 條目本身中重定向輸出,而不是修改 Python 腳本以重定向其自己的輸出:
* * * * * /usr/bin/python3 /home/my_user_folder/Desktop/test/myscript.py > output.txt
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/477613.html
標籤:python-3.x linux cron
