[英]Pipe output of python script
I'm running ./sample.py --url http://blah.com
without error, though if I run ./sample.py --url http://blah.com | wc -l
我正在运行
./sample.py --url http://blah.com
但没有错误,但如果我运行./sample.py --url http://blah.com | wc -l
./sample.py --url http://blah.com | wc -l
or similar I receive an error: ./sample.py --url http://blah.com | wc -l
或类似我收到错误:
UnicodeEncodeError: 'ascii' codec can't encode character u'\' in position 0: ordinal not in range(128)
How do I make a python script compatible with my terminal commands? 如何使python脚本与我的终端命令兼容? I keep seeing reference to
sys.stdin.isatty
though its use case appears to be opposite. 我一直看到对
sys.stdin.isatty
引用,尽管它的用例似乎正好相反。
When Python detects that it is printing to a terminal, sys.stdout.encoding
is set to the encoding of the terminal. 当Python检测到它正在打印到终端时,
sys.stdout.encoding
被设置为终端的编码。 When you print
a unicode
, the unicode
is encoded to a str
using the sys.stdout.encoding
. print
unicode
,使用sys.stdout.encoding
将unicode
编码为str
。
When Python does not detect that it is printing to a terminal, sys.stdout.encoding
is set to None
. 当Python未检测到它正在打印到终端时,
sys.stdout.encoding
设置为None
。 When you print
a unicode
, the ascii
codec is used (at least in Python2). print
unicode
,使用ascii
编解码器(至少在Python2中)。 This will result in a UnicodeError if the unicode
contains code points outside of 0-127. 如果
unicode
包含0-127之外的代码点,则会导致UnicodeError。
One way to fix this is to explicitly encode your unicode
before printing. 解决此问题的一种方法是在打印前对您的
unicode
进行显式编码。 That perhaps is the proper way, but it can be laborious if you have a lot of print statements scattered around. 这也许是正确的方法,但如果你周围散布着很多印刷语句,那就太费力了。
Another way to fix this is to set the PYTHONIOENCODING environment variable to an appropriate encoding. 解决此问题的另一种方法是将PYTHONIOENCODING环境变量设置为适当的编码。 For example,
例如,
PYTHONIOENCODING=utf-8
Then this encoding will be used instead of ascii
when printing output to a file. 然后在将输出打印到文件时将使用此编码而不是
ascii
。
See the PrintFails wiki page for more information. 有关更多信息,请参见PrintFails Wiki页面 。
Try: 尝试:
(./sample.py --url http://blah.com) | wc -l
This spawns a subshell to run your python script then pipes the output from stdout
to wc
这会生成一个子shell来运行你的python脚本,然后将输出从
stdout
传递到wc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.