首页 > 解决方案 > 使用来自 crontab 的参数(来自 python 中的 argparse)运行 python 脚本

问题描述

我有一个 python 脚本,它使用argparse并接受一些参数并从 cron 运行它

例子:python test.py --a apple --b ball

这需要从 crontab 安排。我可以手动运行它,但 cron 无法识别参数。请提出解决方案。

cron 作业线如下所示:

* * * * * /pathtopython/python test.py --a apple --b ball > /tmp/abc.out 2>&1 

标签: pythoncronscheduled-tasks

解决方案


crontest.py文件代码:

导入参数解析

parser = argparse.ArgumentParser()
parser.add_argument('--a', help="First parameter")
parser.add_argument('--b', help="First parameter")
args = parser.parse_args()

file = open('/var/www/html/research/coding-challenge/geek.txt','a') 
file.write("This is the write command") 
file.write("It allows us to write in a particular file") 
file.write(args.a+args.b)

file.close() 

cron 命令:

*/1 * * * * python /var/www/html/crontest.py --a apple --b ballon

重要的事情:不要忘记在 ubuntu 中重新启动 cron。

sudo /etc/init.d/cron restart 

如果您使用不同的操作系统,请检查相关命令以重新启动 cron。


推荐阅读