由cron执行的Django管理命令会导致错误

时间:2013-05-14 06:42:40

标签: django cron debian

我有以下cronjob:

0 0 * * * source /home/admin/data/virtualenvs/myapp/bin/activate && python /home/admin/data/virtualenvs/myapp/project/manage.py 1c-import >> /home/admin/data/logs/1c-import.log 2>&1

因此,在日志文件中,我看到以下错误:

Traceback (most recent call last):
  File "/home/admin/data/virtualenvs/myapp/project/manage.py", line 28, in <module>
    execute_from_command_line(sys.argv)
  File "/home/admin/data/virtualenvs/myapp/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
    utility.execute()
  File "/home/admin/data/virtualenvs/myapp/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/admin/data/virtualenvs/myapp/local/lib/python2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/home/admin/data/virtualenvs/myapp/local/lib/python2.7/site-packages/django/core/management/base.py", line 232, in execute
    output = self.handle(*args, **options)
  File "/home/admin/data/virtualenvs/myapp/project/helper/management/commands/1c-import.py", line 94, in handle
    print 'Product [%s] with price %s and qty %s' % (product_title, product_price, product_qty)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 34-35: ordinal not in range(128)

但是当我尝试手动运行thic命令时 - 没关系。你怎么想 - 可能导致这个错误的原因是什么?

2 个答案:

答案 0 :(得分:4)

问题是cron的语言环境设置不正确。

/etc/environment

LANG=en_US.UTF-8

此链接非常有用:locale setting for cron job

这个问题也是:Python3: UnicodeEncodeError only when run from crontab

答案 1 :(得分:1)

我的猜测是,当从cron作业运行它时,系统会尝试将产品标题,价格和数量转换为ASCII,而在手动运行时会选择不同的编码。 您的一个或多个产品的标题,价格和/或数量都不能编码为ASCII。

如果您打印这样的信息会有帮助吗?:

ENCODING = "utf-8"
print 'Product [%s] with price %s and qty %s' % (product_title.encode(ENCODING), 
                      product_price.encode(ENCODING), product_qty.encode(ENCODING))