Python2 UTF-8 한글 사용

Jmnote bot (토론 | 기여)님의 2020년 11월 2일 (월) 00:52 판 (봇: Jmnote의 2020-03-18T10:46:29Z 에 작성한 570166 판으로 되돌림)

1 개요

Python2 UTF-8 사용
Python2 한글 사용
SyntaxError: Non-ASCII character '\xec'
  • Python 2에서는 UTF-8 한글 사용시 UTF-8 설정을 명시해주어야 함

2 문제상황

root@zetawiki:~# cat hello.py 
print("안녕")
root@zetawiki:~# python3 -V
Python 3.5.2
root@zetawiki:~# python3 hello.py
안녕
root@zetawiki:~# python2 -V
Python 2.7.12
root@zetawiki:~# python2 hello.py
  File "hello.py", line 1
SyntaxError: Non-ASCII character '\xec' in file hello.py on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
→ 파이썬3에서는 정상
→ 파이썬2에서는 오류가 발생함

3 정상 예시

  • 파일의 첫번째 줄에 # -*- coding: utf-8 -*- 추가
  • 해시뱅과 함께 쓸 때는 두번째 줄
root@zetawiki:~# cat hello.py 
# -*- coding: utf-8 -*-
print("안녕")
root@zetawiki:~# python hello.py
안녕
root@zetawiki:~# cat hello.py 
#!/usr/bin/python
# -*- coding: utf-8 -*-
print("안녕")
root@zetawiki:~# ./hello.py
안녕

4 같이 보기

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}