프로그래밍/Python

[Python]UnicodeDecodeError: 'ascii' codec can't decode byte 0xbe in position 0: ordinal not in range(128)

guitarhero 2017. 10. 17. 10:50
728x90

Python 에러


UnicodeDecodeError: 'ascii' codec can't decode byte 0xbe in position 0: ordinal not in range(128) 

위의 에러를 잡는 방법을 우연히 찾게 되서 공유해 본다. 


1. Python이 설치된 경로(e.g. 나의 경우에는 C:\python)의 lib 디렉토리(윈도니까 폴더라고 해야하는 것인가)에 있는 site.py(c:\python\lib\site.py)를 열어 479, 490 라인의 ascii를 utf-8로 수정한다.

def setencoding():

    """Set the string encoding used by the Unicode implementation.  The

    default is 'ascii', but if you're willing to experiment, you can

    change this."""

    encoding = "utf-8" # Default value set by _PyUnicode_Init() 여기

    if 0:

        # Enable to support locale aware default string encodings.

        import locale

        loc = locale.getdefaultlocale()

        if loc[1]:

            encoding = loc[1]

    if 0:

        # Enable to switch off string to Unicode coercion and implicit

        # Unicode to string conversion.

        encoding = "undefined"

    if encoding != "utf-8": # 여기

        # On Non-Unicode builds this will raise an AttributeError...

        sys.setdefaultencoding(encoding) # Needs Python Unicode build !

2.같은 디렉토리의 ntpath.py를 열어 87번째 라인의 p_path를 p_path.encode('utf-8')로 치환해준다.

# Join two (or more) paths.

def join(path, *paths):

    """Join two or more pathname components, inserting "\\" as needed."""

    result_drive, result_path = splitdrive(path)

    for p in paths:

        p_drive, p_path = splitdrive(p)

        if p_path and p_path[0] in '\\/':

            # Second path is absolute

            if p_drive or not result_drive:

                result_drive = p_drive

            result_path = p_path

            continue

        elif p_drive and p_drive != result_drive:

            if p_drive.lower() != result_drive.lower():

                # Different drives => ignore the first path entirely

                result_drive = p_drive

                result_path = p_path

                continue

            # Same drive in different case

            result_drive = p_drive

        # Second path is relative to the first

        if result_path and result_path[-1] not in '\\/':

            result_path = result_path + '\\'

        result_path = result_path + p_path.encode('utf-8') #요기

    ## add separator between UNC and non-absolute path

    if (result_path and result_path[0] not in '\\/' and

        result_drive and result_drive[-1:] != ':'):

        return result_drive + sep + result_path

    return result_drive + result_path

실행만 해도 나오던 오류들이 사라졌다.. 멋지다. ㅋㅋㅋ


[출처]http://blog.lyuwonkyung.com/windows-pipeseo-unicodedecodeerror-balsaeng-2/

728x90