Skip to content

Instantly share code, notes, and snippets.

@embayer
Last active October 30, 2020 06:21
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save embayer/2774afb51b188dc53ed8 to your computer and use it in GitHub Desktop.
Save embayer/2774afb51b188dc53ed8 to your computer and use it in GitHub Desktop.
set python default encoding to utf-8

change default encoding

cd ~/.virtualenvs/myvirtualenv/lib/python2.x/site-packages
echo 'import sys;sys.setdefaultencoding("utf-8")' > sitecustomize.py

set default encoding for each new virtualenv

to automatically create a sitecustomize.py every time you create a virtualenv, edit your

~/.virtualenvs/postmkvirtualenv:

#!/bin/bash
# This hook is run after a new virtualenv is activated.
PY_VERSION=`ls $VIRTUAL_ENV/lib/`
echo 'import sys;sys.setdefaultencoding("utf-8")' > $VIRTUAL_ENV/lib/$PY_VERSION/site-packages/sitecustomize.py

Set the encoding in your Python file

# -*- coding: utf-8 -*-
@yogeesh
Copy link

yogeesh commented Feb 10, 2020

Even after setting all these encoding formats in the file. I am still get encoding related error, do you have any suggestion ?

    print random_stuff_print()
  File "C:\Python27\lib\encodings\cp437.py", line 12, in encode
    return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\xf8' in position 11167: character maps to <undefined>

I added this in beginning of my python file:
# -*- coding: utf-8 -*-

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

@AXGKl
Copy link

AXGKl commented Oct 30, 2020

pip install setdefaultencoding

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment