"Python2 UTF-8 한글 사용"의 두 판 사이의 차이

잔글 (봇: 자동으로 텍스트 교체 (-source +syntaxhighlight))
 
(사용자 2명의 중간 판 18개는 보이지 않습니다)
1번째 줄: 1번째 줄:
;Python UTF-8 사용
{{테스트|Python 2.6, 2.7}}
;Python 한글 사용
==개요==
;Python2 UTF-8 사용
;Python2 한글 사용
;<nowiki>SyntaxError: Non-ASCII character '\xec'</nowiki>
;<nowiki>SyntaxError: Non-ASCII character '\xec'</nowiki>
* Python 2에서는 UTF-8 한글 사용시 UTF-8 설정을 명시해주어야 함


==문제상황==
==문제상황==
*python 소스 코드에 UTF-8 한글이 포함될 경우 오류 발생
<syntaxhighlight lang='console'>
<source lang='dos'>
root@zetawiki:~# cat hello.py  
[root@jmnote ~]# cat hello.py  
print("안녕")
print "안녕"
root@zetawiki:~# python3 -V
[root@jmnote ~]# python hello.py
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
   File "hello.py", line 1
SyntaxError: Non-ASCII character '\xec' in file hello.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
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
</source>
</syntaxhighlight>
:→ 파이썬3에서는 정상
:→ 파이썬2에서는 오류가 발생함


==정상 예시==
==정상 예시==
*파일 맨첫줄에 <code># -*- coding: utf-8 -*-</code> 추가
* 파일의 첫번째 줄에 <code># -*- coding: utf-8 -*-</code> 추가
<source lang='dos'>
* 해시뱅과 함께 쓸 때는 두번째 줄
[root@jmnote ~]# cat hello2.py  
<syntaxhighlight lang='console'>
root@zetawiki:~# cat hello.py
# -*- coding: utf-8 -*-
print("안녕")
root@zetawiki:~# python hello.py
안녕
</syntaxhighlight>
<syntaxhighlight lang='console'>
root@zetawiki:~# cat hello.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
print "안녕"
print("안녕")
[root@jmnote ~]# python hello2.py
root@zetawiki:~# ./hello.py
안녕
안녕
</source>
</syntaxhighlight>


==같이 보기==
==같이 보기==
*[[주석]]
* [[Python nohup 백그라운드 실행시 UTF-8 적용]]
*[[django 설치]]
* [[Python 주석]]
* [[리눅스 쉘 한글 깨짐]]
* [[django 설치]]


[[분류: Python]]
[[분류: Python]]
[[분류: UTF-8]]
[[분류: UTF-8]]
[[분류: 한글]]
[[분류: 한글]]

2020년 11월 2일 (월) 00:56 기준 최신판

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