一段python2脚本, 很简单只是执行一行print语句, 但是print的内容中带有中文.

例如: print(u”测试”)

 

ssh登录到主机之后再运行脚本没有问题, 但是ssh root@host “python test.py”这么执行就会报错:

UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 8-20: ordinal not in range(128)

 

解决方案: print语句会将文本内容传输给tty, 然而ssh执行命令没有默认创建tty. 在不修改python代码的前提下, 解决方法是要么给ssh命令增加-t参数分配tty, 要么增加一个环境变量PYTHONIOENCODING=UTF-8

Leave a Reply

电子邮件地址不会被公开。 必填项已用*标注

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>