2016年6月19日 星期日

[ Python 常見問題 ] Changing default encoding of Python?

Source From Here 
Question 
I have many "can't encode" and "can't decode" problems with Python when I run my applications from the console. But in the Eclipse PyDev IDE, the default character encoding is set to UTF-8, and I'm fine. I searched around for setting the default encoding, and people say that Python deletes the sys.setdefaultencoding function on startup, and we can not use it. 

How-To 
Here is a simpler method (hack) that gives you back the setdefaultencoding() function that was deleted from sys
  1. # sys.setdefaultencoding() does not exist, here!  
  2. import sys  
  3. reload(sys)  # Reload does the trick!  
  4. sys.setdefaultencoding('UTF8')  
PS: 
This is obviously a hack, since sys.setdefaultencoding is purposely removed from sys when Python starts. Reenabling it and changing the default encoding can break code that relies on ASCII being the default (this code can be third-party, which would generally make fixing it impossible or dangerous).

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...