我在 Centos6 远程服务器上通过 cron 作业运行 Python feedparser 脚本(SSH 连接到服务器)。
在 Crontab 中,这是我的 cron 作业:
MAILTO = myemail@company.com
*/10 * * * * /home/local/COMPANY/malvin/SilverChalice_CampusInsiders/SilverChalice_CampusInsiders.py > /home/local/COMPANY/malvin/SilverChalice_CampusInsiders`date +\%Y-\%m-\%d-\%H:\%M:\%S`-cron.log | mailx -s "Feedparser Output" myemail@company.com
但是,我在发送的电子邮件中看到这条消息,它应该只包含脚本的输出:
Null message body; hope that's ok
/usr/lib/python2.7/site-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning
Traceback (most recent call last):
File "/home/local/COMPANY/malvin/SilverChalice_CampusInsiders/SilverChalice_CampusInsiders.py", line 70, in <module>
BC_01.createAndIngest(name, vUrl, tags, desc)
File "/home/local/COMPANY/malvin/SilverChalice_CampusInsiders/BC_01.py", line 69, in createAndIngest
creds = loadSecret()
File "/home/local/COMPANY/malvin/SilverChalice_CampusInsiders/BC_01.py", line 17, in loadSecret
credsFile=open('brightcove_oauth.json')
IOError: [Errno 2] No such file or directory: 'brightcove_oauth.json'
通常,这将是一个无需思考的问题:我的代码一定有问题。除了,当我通过 python SilverChalice_CampusInsiders.py
我在这里做错了什么?为什么 Python 脚本在通过 cron 作业运行时“看不到”json oauth 文件?
最佳答案
Cron 为作业设置了一个最小环境(我认为它从主目录运行作业)。
在你的 python 脚本中,当你做类似的事情时 -
open('<filename>')
它检查当前工作目录中的文件名
,而不是您的脚本所在的目录。
即使从命令行运行时也是如此,如果您将目录更改为其他目录(可能是您的主目录),然后使用脚本的绝对路径来运行它,您应该会遇到相同的错误。
您可以尝试以下任一选项,而不是依赖于正确的当前工作目录和您要打开的文件 -
要打开的文件使用绝对路径,不要使用相对路径。
或者如果以上不是您的选择,并且您要打开的文件相对于正在运行的脚本存在(例如,目的是在同一目录中),那么您可以使用
__file__
(这给出了脚本位置)和os.path
, 在运行时创建文件的绝对路径,示例 -import os.path fdir = os.path.abspath(os.path.dirname(__file__)) #This would give the absolute path to the directory in which your script exists. f = os.path.join(fdir,'<yourfile')
最后 f
将有您的文件的路径,您可以使用它来打开您的文件。
关于通过返回 IOError [错误 2] 的 cron 作业运行的 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31622520/