如何在python上改变stdin编码 [英] How to change the stdin encoding on python

查看:167
本文介绍了如何在python上改变stdin编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为同一个项目使用Windows和linux机器。 windows上stdin的默认编码是cp1252,而linux是utf-8。



我想将所有内容更改为uft-8。
有可能吗?如何做?



感谢
Eduardo

解决方案

p>您可以通过在打印时不依赖于隐式编码来执行此操作。在任何情况下,不依赖这一点是一个好主意 - 隐式编码仅在打印到stdout时使用,当stdout连接到终端时。



更好的方法是使用 unicode 到处,并使用 codecs.open codecs.getwriter 无处不在您将 c> sys.stdout 包含在使用例如:



<$的自动将Unicode字符串字符串编码为UTF-8的对象中p $ p> sys.stdout = codecs.getwriter('utf-8')(sys.stdout)

但是,如果您使用unicode,这只能工作。所以,使用unicode无处不在。真的,无处不在。


I'm using windows and linux machines for the same project. The default encoding for stdin on windows is cp1252 and on linux is utf-8.

I would like to change everything to uft-8. Is it possible? How can I do it?

Thanks Eduardo

解决方案

You can do this by not relying on the implicit encoding when printing things. Not relying on that is a good idea in any case -- the implicit encoding is only used when printing to stdout and when stdout is connected to a terminal.

A better approach is to use unicode everywhere, and use codecs.open or codecs.getwriter everywhere. You wrap sys.stdout in an object that automatically encodes your unicode strings into UTF-8 using, for example:

sys.stdout = codecs.getwriter('utf-8')(sys.stdout)

This will only work if you use unicode everywhere, though. So, use unicode everywhere. Really, everywhere.

这篇关于如何在python上改变stdin编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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