Python2 UTF-8 한글 사용

(Python UTF-8 한글 사용에서 넘어옴)

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 }}