Setting the correct encoding when piping stdout in Python

后端 未结 10 2422
迷失自我
迷失自我 2020-11-22 01:21

When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this:

# -*- co         


        
10条回答
  •  北海茫月
    2020-11-22 01:56

    export PYTHONIOENCODING=utf-8
    

    do the job, but can't set it on python itself ...

    what we can do is verify if isn't setting and tell the user to set it before call script with :

    if __name__ == '__main__':
        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)
    

    Update to reply to the comment: the problem just exist when piping to stdout . I tested in Fedora 25 Python 2.7.13

    python --version
    Python 2.7.13
    

    cat b.py

    #!/usr/bin/env python
    #-*- coding: utf-8 -*-
    import sys
    
    print sys.stdout.encoding
    

    running ./b.py

    UTF-8
    

    running ./b.py | less

    None
    

提交回复
热议问题