python脚本的管道输出 [英] Pipe output of python script

查看:213
本文介绍了python脚本的管道输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行./sample.py --url http://blah.com,没有错误,但是如果运行./sample.py --url http://blah.com | wc -l或类似的命令,则会收到错误消息:

I'm running ./sample.py --url http://blah.com without error, though if I run ./sample.py --url http://blah.com | wc -l or similar I receive an error:

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

如何使python脚本与我的终端命令兼容?我一直看到对sys.stdin.isatty的引用,尽管它的用例似乎相反.

How do I make a python script compatible with my terminal commands? I keep seeing reference to sys.stdin.isatty though its use case appears to be opposite.

推荐答案

当Python检测到它正在打印到终端时,将sys.stdout.encoding设置为终端的编码. print a unicode时,使用sys.stdout.encodingunicode编码为str.

When Python detects that it is printing to a terminal, sys.stdout.encoding is set to the encoding of the terminal. When you print a unicode, the unicode is encoded to a str using the sys.stdout.encoding.

当Python未检测到正在打印到终端时,将sys.stdout.encoding设置为None.当printunicode时,将使用ascii编解码器(至少在Python2中).如果unicode包含0-127以外的代码点,则将导致UnicodeError.

When Python does not detect that it is printing to a terminal, sys.stdout.encoding is set to None. When you print a unicode, the ascii codec is used (at least in Python2). This will result in a UnicodeError if the unicode contains code points outside of 0-127.

解决此问题的一种方法是在打印前对unicode进行显式编码.那也许是正确的方法,但是如果周围有很多打印语句,可能会很费力.

One way to fix this is to explicitly encode your unicode before printing. That perhaps is the proper way, but it can be laborious if you have a lot of print statements scattered around.

解决此问题的另一种方法是设置 PYTHONIOENCODING 环境变量进行适当的编码.例如,

Another way to fix this is to set the PYTHONIOENCODING environment variable to an appropriate encoding. For example,

PYTHONIOENCODING=utf-8

然后,在将输出打印到文件时,将使用此编码而不是ascii.

Then this encoding will be used instead of ascii when printing output to a file.

有关更多信息,请参见 PrintFails Wiki页面.

See the PrintFails wiki page for more information.

这篇关于python脚本的管道输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆