【问题标题】:Python script encoding trouble when run in CRON job在 CRON 作业中运行时 Python 脚本编码问题
【发布时间】:2012-08-07 09:11:07
【问题描述】:

正如许多人所希望的那样,这个编码问题正在驱使我精神。我真的很感激对此有所了解!

最终目标是能够从终端和 cron 以及带有 > stdout.txt 的 cron 运行相同的 script.py。不用说,我遇到了严重的编码问题。

因此,我的 script.py 从终端运行良好:python script.py
但是,当从终端运行时,它会引发错误:python script.py > stdout.txt
无论哪种方式,在 cron 中运行时都会引发相同的错误。

我有一个 python 脚本,以 root 身份输入 crontab -e

这是我的 script.py 标头:

#!/usr/bin/python
# -*- coding: utf-8 -*-

这是我的 cron 条目:

* * * * * python /home/ubuntu/parrot/script.py > /home/ubuntu/parrot/stdout.txt

这是我的 stdout.txt(相关部分):

Unexpected error!  (<type 'exceptions.UnicodeDecodeError'>, UnicodeDecodeError('ascii', 'blabla some weird text n\xc3\xa5r end', 54, 55, 'ordinal not in range(128)')) 

这是我来自终端的环境(相关部分):

LANG=en_US.UTF-8

这是我的 cron 环境(相关部分):

LANG=en_US.UTF-8

这是 script.py 中引发错误的(第一)行:

print 'Posting @%s: %s' % (statusObj.user.screen_name.encode('ascii', 'replace'), statusObj.text.encode('utf-8', 'replace'))

编辑: sys.getdefaultencoding() 返回ascii

非常感谢任何帮助!

【问题讨论】:

标签: python utf-8 cron


【解决方案1】:

如果您可以控制statusObj,您应该检查将数据解析到对象中的相关代码,并尝试尽可能clean 获取输入。

在尝试对其进行编码之前,您要确保将字符串解码为 un​​icode。

如果不行你可以试试:

# try to get the string into unicode
screen_name = unicode(statusObj.user.screen_name) 
post = unicode(statusObj.text) # probably an error here?
output_str = u"Posting @{name}: {post}".format(name=screen_name, post=post)
print output_str.encode("utf8", "replace") # encode the unicode string on 

【讨论】:

  • 但我的代码已经在 CLI 中运行。所以它必须与cron的编码环境有关?我会尝试的。谢谢!
  • 我刚刚将 sys.stdout = codecs.getwriter('utf8')(sys.stdout) 添加到顶部并完全删除了 .encode'ings。问题解决了!非常感谢大家! =)
猜你喜欢
  • 2012-11-01
  • 2011-12-05
  • 1970-01-01
  • 1970-01-01
  • 2014-02-02
  • 1970-01-01
  • 2018-08-23
  • 1970-01-01
  • 2021-11-16
相关资源
最近更新 更多