search

Home  >  Q&A  >  body text

字符编码 - python2.7在使用reload(sys)后,再使用print语句无输出,有解决办法吗?

为了解决此问题
解决Python2.7的UnicodeEncodeError: ‘ascii’ codec can’t encode异常错误
从而在代码中使用了reload(sys)
但在此句过后,print语句无法正常输出内容,有办法解决吗?
>>> print 123
123
>>> print sys.getdefaultencoding()
cp936
>>> reload(sys)
>>> print sys.getdefaultencoding()
>>> print 123
>>>

阿神阿神2803 days ago893

reply all(1)I'll reply

  • 阿神

    阿神2017-04-17 13:04:51

    You should be running it under idle? It cannot print because the stdout of idle is not the default stdout, so all the output to stdout after reload(sys) cannot be seen. You can consider the following code to change stdout back after reload(sys)

    import sys
    stdout = sys.stdout
    reload(sys)
    sys.stdout = stdout
    

    Similarly, we also need to do the same processing for stdin and stderr

    reply
    0
  • Cancelreply