如果命令行程序不确定stdout的编码,应该输出什么编码? [英] If a command line program is unsure of stdout's encoding, what encoding should it output?

查看:203
本文介绍了如果命令行程序不确定stdout的编码,应该输出什么编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Python写的一个命令行程序,当我用管道通过命令行上的其他程序, sys.stdout.encoding None 。这是有道理的,我想 - 输出可以是另一个程序或您要重定向到文件中,或什么的,它不知道需要何种编码。但我也不!这个程序将被许多不同的人(幽默我)以不同的方式使用。我应该玩它安全,只输出ascii(用问号替换非ascii字符)?或者我应该输出UTF-8,因为它是如此普遍,这些天?

I have a command line program written in Python, and when I pipe it through another program on the command line, sys.stdout.encoding is None. This makes sense, I suppose -- the output could be another program, or a file you're redirecting it into, or whatever, and it doesn't know what encoding is desired. But neither do I! This program will be used by many different people (humor me) in different ways. Should I play it safe and output only ascii (replacing non-ascii chars with question marks)? Or should I output UTF-8, since it's so widespread these days?

推荐答案

我建议你使用当前的语言环境。

I suggest you use the current locale.

Python2> import locale
Python2> locale.getpreferredencoding()
'UTF-8'

系统知道应该,而另一方,如果它也使用当前语言环境,将做正确的事情。

The system knows what it should be, and the other side, if it also uses the current locale, will do the right thing.

这篇关于如果命令行程序不确定stdout的编码,应该输出什么编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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