Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default encoding in Python (setdefaultencoding() function does not exist)? [duplicate]

Possible Duplicate:
Changing default encoding of python?

I am reading dive in python and it mentions setting python's default encoding scheme in the XML parsing chapter.

The setdefaultencoding is used in python-installed-dir/site-packages/pyanaconda/sitecustomize.py

import sys
sys.setdefaultencoding('utf-8')

But when I run the script, it raises:

AttributeError: 'module' object has no attribute 'setdefaultencoding'

How to set the default encoding,anyway?

I am using python 2.7

Solution: find the site.py in the python installation.

Edit the setencoding function

def setencoding():
    encoding = "ascii" 
    if 0:
        import locale
        loc = locale.getdefaultlocale()
        if loc[1]:
            encoding = loc[1]
    if 0: #changes comes here, change 0 to 1
        encoding = "undefined" #the encoding you want
    if encoding != "ascii":
        sys.setdefaultencoding(encoding) 

I am using python 2.7

like image 251
xiaohan2012 Avatar asked Aug 18 '11 09:08

xiaohan2012


People also ask

How do you change the codec in Python?

Under Eclipse, run dialog settings ("run configurations", if I remember correctly); you can choose the default encoding on the common tab. Change it to US-ASCII if you want to have these errors 'early' (in other words: in your PyDev environment).


1 Answers

Python's sys module has had a setdefaultencoding function since Python 2.0. However,

This function is only intended to be used by the site module implementation and, where needed, by sitecustomize. Once used by the site module, it is removed from the sys module’s namespace.

The docs back to at least Python 2.1 indicate this happens, so it was never appropriate for PyAnaconda to use this method, and I'm not sure why it ever worked.

like image 164
agf Avatar answered Sep 19 '22 15:09

agf