Why should we NOT use sys.setdefaultencoding(“utf-8”) in a py script?

前端 未结 4 1434
孤街浪徒
孤街浪徒 2020-11-22 03:11

I have seen few py scripts which use this at the top of the script. In what cases one should use it?

import sys
reload(sys)
sys.setdefaultencoding(\"utf-8\")         


        
4条回答
  •  旧巷少年郎
    2020-11-22 03:49

    #!/usr/bin/env python
    #-*- coding: utf-8 -*-
    u = u'moçambique'
    print u.encode("utf-8")
    print u
    
    chmod +x test.py
    ./test.py
    moçambique
    moçambique
    
    ./test.py > output.txt
    Traceback (most recent call last):
      File "./test.py", line 5, in 
        print u
    UnicodeEncodeError: 'ascii' codec can't encode character 
    u'\xe7' in position 2: ordinal not in range(128)
    

    on shell works , sending to sdtout not , so that is one workaround, to write to stdout .

    I made other approach, which is not run if sys.stdout.encoding is not define, or in others words , need export PYTHONIOENCODING=UTF-8 first to write to stdout.

    import sys
    if (sys.stdout.encoding is None):            
        print >> sys.stderr, "please set python env PYTHONIOENCODING=UTF-8, example: export PYTHONIOENCODING=UTF-8, when write to stdout." 
        exit(1)
    


    so, using same example:

    export PYTHONIOENCODING=UTF-8
    ./test.py > output.txt
    

    will work

提交回复
热议问题