通过cron作业运行的Python脚本返回了IOError [错误2]

Adj*_*con 1 python cron python-2.7 centos6

我正在Centos6远程服务器(通过SSH进入服务器)上通过cron作业运行Python feedparser脚本。

在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
Run Code Online (Sandbox Code Playgroud)

但是,我在正在发送的电子邮件中看到此消息,该消息应该只包含脚本的输出:

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'
Run Code Online (Sandbox Code Playgroud)

通常,这将是不费吹灰之力的问题:我的代码一定有问题。除此之外,当我通过以下命令在命令行上运行脚本时,脚本可以正常运行python SilverChalice_CampusInsiders.py

我在这里做错了什么?通过cron作业运行时,为什么Python脚本没有“看到” json oauth文件?

Ana*_*mar 5

Cron为作业设置了最小的环境(我认为它从主目录运行作业)。

在python脚本中,当您执行类似操作时-

open('<filename>')
Run Code Online (Sandbox Code Playgroud)

它检查filename当前工作目录中的,而不是脚本所在的目录。

即使从命令行运行,也是如此,如果将目录更改为其他目录(可能是主目录),然后使用脚本的绝对路径来运行它,则应该得到相同的错误。

您可以尝试以下任一选项,而不是依赖当前的工作目录正确无误并拥有要打开的文件:

  1. 使用您要打开的文件的绝对路径,不要使用相对路径。

  2. 或者,如果以上都不是您的选择,并且要打开的文件相对于正在运行的脚本存在(例如,让我们在同一目录中说),那么您可以使用__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')
    
    Run Code Online (Sandbox Code Playgroud)

最后f会有文件的路径,您可以使用它来打开文件。