# -*- coding: utf-8 -*-
# 파이썬3 에선 모든 문자열을 UTF-8 로 처리합니다
# 그래서 소스코드가 UTF-8 이 아닌경우에는 실행시 에러가 발생합니다
# 그래서
# 한국어 환경에서 프로그래밍을 할때에,
# 파이썬 코드에 입력된 문자가 정확히 어떤 문자셋인지 식별을 도와주는 코드입니다
# 본 코드는 우분투 18.04 LTS 파이썬 3.6.9 에서 실험 했습니다.
# 실험을 위하야 작업디렉토리에 임의의 파일 cp949/ascii/utf-8 등 다양한 파일들을 준비했습니다
import io
import subprocess
"""
참고문헌:
[1] https://docs.python.org/ko/3/library/codecs.html#standard-encodings
[2] https://stackoverflow.com/questions/436220/how-to-determine-the-encoding-of-text
"""
# 한국어환경과 관련된 모든 인코딩
encodings = [
"ascii",
"cp949",
"euc_kr",
"iso2022_kr",
"utf_8",
]
def coding_id(file):
for e in encodings:
try:
fh = io.open(file, "r", encoding=e)
fh.readlines()
fh.seek(0)
except UnicodeDecodeError:
print("got unicode error with %s, trying different encoding" % e)
else:
print("opening the file [%s] with encoding: [%s] \n" % (file, e))
break
search_py = "ls *.py" # 작업디렉토리에서 파이썬 소스코드 파일만 찾습니다
cmd_ls = subprocess.Popen(search_py, stdout=subprocess.PIPE, shell=True)
output = cmd_ls.communicate()[0]
file_list = output.decode("utf-8").split()
for file in file_list:
coding_id(file)
# EOF
[우분투 18.04 파여폭스 나비에서 작성했습니다]