V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
exoticknight
V2EX  ›  问与答

python 的 print 跨平台问题

  •  
  •   exoticknight · 2015-03-19 13:40:50 +08:00 · 2476 次点击
    这是一个创建于 3319 天前的主题,其中的信息可能已经有所发展或是发生改变。
    在写一python脚本,大致做的事情是取到网页后用bs4选取内容输出。
    那么问题来了。
    已经在开头加上# -*- coding: utf-8 -*-,并且文件是utf-8编码。
    print的时候,windows下需要使用encode,而Linux下不用。
    然而我希望同一个脚本能在windows和Linux上都能运行,应该怎么办?
    每次print都判断好像很蠢的样子……
    谢谢大家。
    10 条回复    2015-03-20 22:33:58 +08:00
    loading
        1
    loading  
       2015-03-19 14:07:11 +08:00   ❤️ 1
    你输出到log文件就好很多了,试试。
    clino
        2
    clino  
       2015-03-19 14:12:33 +08:00   ❤️ 1
    包装一个函数,将字符串都尝试decode成unicode以后再print
    因为print u"中文" 在两个平台上都是可以的
    Sylv
        3
    Sylv  
       2015-03-19 14:34:55 +08:00 via iPhone
    Sylv
        4
    Sylv  
       2015-03-19 14:38:25 +08:00 via iPhone   ❤️ 1
    想要跨环境的话,这是一种解决办法:
    print unicode.encode(sys.stdout.encoding)
    exoticknight
        5
    exoticknight  
    OP
       2015-03-19 17:10:29 +08:00
    @clino
    @Sylv
    直接使用u"...."能打印出来一部分
    但是遇到符号'・',就出问题了,编码是/u30fb
    似乎是gbk没有这个符号?
    使用了encode('gb18030')之后虽然变成了??,但是起码看不到可恶的UnicodeEncodeError……
    icedx
        6
    icedx  
       2015-03-19 17:22:20 +08:00 via Android   ❤️ 1
    封装print
    clino
        7
    clino  
       2015-03-19 17:27:55 +08:00
    @exoticknight windows下只能支持gb码的打印?如果是这样的话,弄一个gb码里没有的字符当然打不出来了
    66450146
        8
    66450146  
       2015-03-19 17:32:21 +08:00
    用 vagrant 运行就好了。。。。
    9hills
        9
    9hills  
       2015-03-19 17:44:06 +08:00 via iPhone
    和平台无关……
    aaaa007cn
        10
    aaaa007cn  
       2015-03-20 22:33:58 +08:00   ❤️ 1
    @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")
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   945 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 22:28 · PVG 06:28 · LAX 15:28 · JFK 18:28
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.