Dmitry Belaventsev
Dmitry Belaventsev

Reputation: 6657

Django managment command executed by cron cause an error

I have the following 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

So, in log file I see following error:

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)

But when I try to manually run thic command - it's ok. What do you think - what may cause this error?

Upvotes: 1

Views: 470

Answers (2)

Rohan
Rohan

Reputation: 53336

The problem would be that locale for the cron is not set properly.

In /etc/environment set

LANG=en_US.UTF-8

This link will be useful: locale setting for cron job

And this question also: Python3: UnicodeEncodeError only when run from crontab

Upvotes: 4

Divisible by Zero
Divisible by Zero

Reputation: 2654

My guess is that when running it from a cron job the system tries to convert you product title, price and quantity to ASCII, while it chooses a different encoding when you run it manually. One or more of your products will have a character in it's title, price and/or quantity which can't be encoded to ASCII.

Does it help if you print the info like this?:

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

Upvotes: 1

Related Questions