Skip to content

Instantly share code, notes, and snippets.

@embayer
Last active October 30, 2020 06:21
Show Gist options
  • Select an option

  • Save embayer/2774afb51b188dc53ed8 to your computer and use it in GitHub Desktop.

Select an option

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

yogeesh commented Feb 10, 2020

Copy link
Copy Markdown

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

axgkl commented Oct 30, 2020

Copy link
Copy Markdown

pip install setdefaultencoding

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