Val*_*nce 6 python ubuntu cron crontab python-3.x
我有一个位于/ home/valence /的python3脚本,可以从Yahoo!获取当天的天气预报(最高和最低温度值,以摄氏度为单位).天气API.该文件看起来完全像这样:
#!/usr/bin/python3
from urllib import request
import json
url="https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%3D349859%20and%20u='c'&format=json&diagnostics=true&callback="
response=request.urlopen(url)
str_response = response.readall().decode('utf-8')
dic = json.loads(str_response)
dic["query"]["results"]["channel"]["location"]["region"]="R.M."
low=dic["query"]["results"]["channel"]["item"]["forecast"][0]["low"]
high=dic["query"]["results"]["channel"]["item"]["forecast"][0]["high"]
forecast=open("forecast.txt", "w+")
forecast.write("Minima: "+str(low)+" Maxima: "+str(high))
forecast.close()
Run Code Online (Sandbox Code Playgroud)
我执行它时工作正常.它使用正确的值创建或覆盖文件forecast.txt,但是当我尝试使用cron执行以下cron作业时:
* * * * * /home/valence/Get_forecast.py
Run Code Online (Sandbox Code Playgroud)
没有文件forecast.txt被创建或修改.
所以我需要知道我做错了什么,以及如何使这项工作按预期进行.cron作业并不是每分钟都要执行一次(因为一天中的预测保持不变),但是现在我已经这样做了,所以我可以看到变化,而不必等待太多.
注意:我是linux新手(我使用的是Lubuntu)
小智 9
使用crontab作业时,forecast.txt在目录中没有获取文件的原因是cron不在目录中执行命令,而是在程序中以相对路径形式指定了文件.所以该文件是在其他地方创建的./home/valence* * * * * /home/valence/Get_forecast.py/home/valenceforecast.txt
要获得预期的文件输出,可以使用以下crontab作业:
* * * * * cd /home/valence && ./Get_forecast.py
Run Code Online (Sandbox Code Playgroud)
这显式地指定当前工作目录/home/valence,并从那里执行脚本.
更重要的是,要从stdout和stderr获取输出,添加重定向在发生意外情况时总是有用的:
* * * * * cd /home/valence && ./Get_forecast.py > /tmp/forecast.log 2>&1
Run Code Online (Sandbox Code Playgroud)
注意:
前两个crontab作业假设Get_forecast.py jexecutable并指定了shebang.该./Get_forecast.py部分可以随时被替换python3 Get_forecast.py或/usr/bin/python3 Get_forecast.py更清晰.