运行bash脚本(运行python脚本)的Cron作业,其行为与直接执行时不同

2024-04-25 21:39:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python脚本,可以创建csv并将其保存到:

file = example.csv
fileDone = os.path.abspath('/home/bw/temp/%s'%file1)

with open(fileDone, 'w+') as myFile:
    a = csv.writer(myFile, delimiter=',')
    a.writerow(['login report for %s from %s to %s:\n\n'%(name[0],start_date,end_date)])
    dato = ['Username','Logins','Platform']
    a.writerow(dato)
    for vizL in vizList:
        data =[str(vizL[0]),str(vizL[1]),"Viz"]
        a.writerow(data)
    for appL in appList:
        data =[str(appL[0]),str(appL[1]),"Analytics"]
        a.writerow(data)

然后bash脚本调用python脚本:

^{pr2}$

然后cron每天运行bash脚本。在

当我手动运行bash脚本时,一切正常,日期也正确。但是当它由cron运行时,它似乎不会覆盖csv文件,而是发送一个已经在/temp文件夹中的文件。所以我假设它没有重新生成csv,因此不运行python脚本。在

这是我第一次设置cron作业来运行运行运行python脚本的bash脚本。对于为什么会发生这种情况,任何潜在的洞察都将不胜感激。在


Tags: csv脚本bashfordatadatemyfiletemp
2条回答

首先,我要确保您的cron使用bash;默认情况下它使用sh。在

有两件事我会尝试:

首先,尝试在bash脚本中设置python脚本的完整路径,如下所示:

#!/bin/bash
python /home/user/scripts/scriptname.py
REPORT_MONTH=`/bin/date "+%d %B %Y"`
echo -e "Attached is the login reports for $REPORT_MONTH\n\n\n\n\n\nGenerated by: $0" | mutt -a /home/bw/temp/example.csv -c my@email.com -s "Daily Login Reports For $REPORT_MONTH"

其次,如果前一个不起作用,可能是cron作业没有覆盖文件的权限。cron在哪个用户下运行?(通常是根)。你能发布crontab -l的输出吗?如果您删除文件并让cron创建它,它会被创建吗?在

相关问题 更多 >