如何使用python和crontab计划作业?

时间:2015-01-11 13:05:09

标签: python django crontab

我想使用python,django和crontab发送自动邮件。所以我做了以下事情。

创建了一个cron_tab.py(位于home / myhome / django / myapp / registration / cron_tab.py文件夹中),如下所示:

from django.core.mail import send_mail, EmailMessage,EmailMultiAlternatives

subject, from_email, to = 'hello', 'testmailing@gmail.com', 'robert@gmail.com'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()

使用终端我通过发出以下命令

进入crontab
crontab -e

我安排了像

这样的任务
* 1 * * *  /home/myhome/django/myapp/registration/cron_tab.py

但我没有收到邮件。我究竟做错了什么?请有人帮助我。更改文件模式后,我收到以下错误并粘贴了追溯

 myhome@myhome:~/django/myapp/registration$ ./cron_tab.py
 from: can't read /var/mail/django.core.mail
 ./cron_tab.py: line 3: subject: command not found
 ./cron_tab.py: line 4: from_email: command not found
 ./cron_tab.py: line 5: to: command not found
 ./cron_tab.py: line 6: text_content: command not found
 ./cron_tab.py: line 7: html_content: command not found
 ./cron_tab.py: line 8: syntax error near unexpected token `('
 ./cron_tab.py: line 8: `msg = EmailMultiAlternatives(subject, text_content, from_email,
 [to])'

3 个答案:

答案 0 :(得分:2)

我认为您cron_tab.py没有从setting.py读取django配置。然后从shell运行此脚本会发生什么?

无论如何,你应该考虑使用custom management command来完成这项任务。

答案 1 :(得分:2)

问题是您使用的Python脚本可能不是可执行文件,并且它不会在该行的第一行声明可执行文件。

您有两种选择:

1)在cron调用中添加python解释器(在本例中,python解释器位于/ usr / bin / python中:

  • 1 * * * / usr / bin / python /home/myhome/django/myapp/registration/cron_tab.py

2)使python脚本可执行(2.1 + 2.2)

2.1.-使文件可执行

$ chmod + x /home/myhome/django/myapp/registration/cron_tab.py

2.2.-编辑文件并在解释器中的第一行声明:

#!/usr/bin/python
from django.core.mail import send_mail, EmailMessage,EmailMultiAlternatives

答案 2 :(得分:1)

  1. 检查您的Python脚本是否可以单独执行它。
  2. 检查您的Python脚本是否可以通过在./cron_tab.py目录上运行/home/myhome/django/myapp/registration/来执行。如果这不起作用,请在命令行的任何位置执行:chmod +x /home/myhome/django/myapp/registration/cron_tab.py,确保脚本以#!/usr/bin/env python指向Python解释器开头。
  3. 如果您没有使用Django的任何其他功能(如模型,查询集等),这种发送电子邮件的方法应该作为一个单独的脚本,不知道任何来自Django的内容。另一方面,如果使用某些Django功能,您将有两种方法来运行此脚本:

    a)作为management command =&gt;如果使用这种方法,我建议您为crontab创建一个单独的脚本,该脚本只运行:

    cd /home/myhome/django/

    python manage.py <your_command>(在这种情况下:)

    b)作为加载Django配置的Python脚本=&gt;您可以直接使用脚本运行。