使用utf-8和nohup的python print语句

时间:2011-04-11 20:11:33

标签: python utf-8 nohup

我有一些打印日志消息的python代码。在命令行运行时,使用utf-8就可以了。包含特殊字符的日志消息打印正常。但是,当在nohup下在后台运行时,它会在utf-8字符上进行barfs。

nohup python2.7 myProgram.py &

我看到的错误是通常的“尝试在ascii中编码utf”错误:

  

UnicodeEncodeError:'ascii'编解码器   无法对字符u'\ u2013'进行编码   第71位:序数不在范围内(128)

我认为这是因为nohup向python发出信号,表示它没有正常的终端,因此默认为ascii。是否有任何方法可以告诉nohup在启用utf-8的情况下运行或者设置它以便utf-8字符在后台运行nohup时不会导致崩溃?

1 个答案:

答案 0 :(得分:19)

使用PYTHONIOENCODING

export PYTHONIOENCODING=utf-8
nohup python2.7 myProgram.py &

例如,如果

<强> myProgram.py

unicode_obj=u'\N{INFINITY}'
print(unicode_obj)    

然后运行

nohup python2.7 myProgram.py > /tmp/test &

产生

<强>的/ tmp /测试

UnicodeEncodeError: 'ascii' codec can't encode character u'\u221e' in position 0: ordinal not in range(128)

,而

export PYTHONIOENCODING=utf-8
nohup python2.7 myProgram.py > /tmp/test &

产生

<强>的/ tmp /测试