python 的 print 跨平台问题

2015 年 3 月 19 日
 exoticknight
在写一python脚本,大致做的事情是取到网页后用bs4选取内容输出。
那么问题来了。
已经在开头加上# -*- coding: utf-8 -*-,并且文件是utf-8编码。
print的时候,windows下需要使用encode,而Linux下不用。
然而我希望同一个脚本能在windows和Linux上都能运行,应该怎么办?
每次print都判断好像很蠢的样子……
谢谢大家。
3032 次点击
所在节点    问与答
10 条回复
loading
2015 年 3 月 19 日
你输出到log文件就好很多了,试试。
clino
2015 年 3 月 19 日
包装一个函数,将字符串都尝试decode成unicode以后再print
因为print u"中文" 在两个平台上都是可以的
Sylv
2015 年 3 月 19 日
Sylv
2015 年 3 月 19 日
想要跨环境的话,这是一种解决办法:
print unicode.encode(sys.stdout.encoding)
exoticknight
2015 年 3 月 19 日
@clino
@Sylv
直接使用u"...."能打印出来一部分
但是遇到符号'・',就出问题了,编码是/u30fb
似乎是gbk没有这个符号?
使用了encode('gb18030')之后虽然变成了??,但是起码看不到可恶的UnicodeEncodeError……
icedx
2015 年 3 月 19 日
封装print
clino
2015 年 3 月 19 日
@exoticknight windows下只能支持gb码的打印?如果是这样的话,弄一个gb码里没有的字符当然打不出来了
66450146
2015 年 3 月 19 日
用 vagrant 运行就好了。。。。
9hills
2015 年 3 月 19 日
和平台无关……
aaaa007cn
2015 年 3 月 20 日
@exoticknight
https://docs.python.org/2/library/codecs.html#codecs.encode
Errors may be given to set the desired error handling scheme. The default error handler is 'strict' meaning that encoding errors raise ValueError (or a more codec specific subclass, such as UnicodeEncodeError). Refer to Codec Base Classes for more information on codec error handling.
比如 print u"・".encode(errors="backslashreplace")

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/177986

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX