正如许多人所希望的那样,这个编码问题正在困扰我精神。我真的很感激对此的一些了解!
最终目标是能够从终端和 cron 以及使用 > stdout.txt
从 cron 运行相同的 script.py。不用说,我遇到了严重的编码问题。
我的 script.py 从终端运行良好:python script.py
但是,当从终端运行时,它会抛出错误:python script.py > stdout.txt
无论哪种方式,在 cron 中运行时都会抛出相同的错误。
我有一个 python 脚本,以 root 身份在 crontab -e
中输入。
这是我的 script.py header :
#!/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
非常感谢任何帮助!
最佳答案
如果您可以控制 statusObj
,您应该检查将数据解析到对象中的相关代码,并尝试使输入尽可能干净。
在尝试编码之前,您需要确保字符串已解码为 unicode。
如果没有你可以尝试:
# 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
关于在 CRON 作业中运行时 Python 脚本编码出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11837748/