在 CRON 作业中运行时 Python 脚本编码出现问题

标签 python utf-8 cron

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

最终目标是能够从终端和 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,您应该检查将数据解析到对象中的相关代码,并尝试使输入尽可能干净

在尝试编码之前,您需要确保字符串已解码为 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 

关于在 CRON 作业中运行时 Python 脚本编码出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11837748/

相关文章:

linux - cron 脚本中的各种 rsync 命令用于同步 Ubuntu 和 Mac 主目录

python - 从列表中的元组中剥离字符

python - Python 中的 MATLAB ind2sub 等价物

python - 如何修复Python中的 'TypeError: expecting string or bytes object'错误

Python 统一码 : how to replace character that cannot be decoded using utf8 with whitespace?

java - 一个32个字符的字符串如何变成46个字节?

ios - 当查询参数包含&符号时编码 NSURL

python - 如何读取包含16位十六进制值的文件?

关于缓存新产品的 Magento 添加到购物车问题

java - Quartz cron 表达式在周六的不同时间运行