본문 바로가기
Development/Python

Black: Uncompromising Python Coding Convetion

by IMCOMKING 2020. 2. 4.

Black: Uncompromising Python Coding Convetion

Python의 coding convention에 따라서 강제로 현재의 소스코드를 reformatting 시켜주는 오픈소스프로젝트이다.

Window에서 Pycharm anaconda 환경에서 setup하기

pipi install black

C:\ProgramData\Anaconda3\Scripts\black.exe 경로 복사

Pycharm에서 File-Setting-Tools-External Tools에서 추가버튼 누르고, 다음을 입력


Name: Black

Description: Black is the uncompromising Python code formatter.

Program: <복사한 경로 입력>

Arguments: "$FilePath$"


사용법: Tools - External Tools - black 클릭
또는 단축키 등록을 한다.



그런데 기본적인 black은 무조건 파일 단위로, 전체 파일에 대해서 reformatting을 시킨다. 오픈소스 혹은 특정한 이유로 다른 영역의 소스코드는 건드리지 않고 일부분에 대해서만 reformatting을 하고 싶은 경우 다른 방법이 필요하다.


Partial Black: 일부 line에 대해서만 reformatting하기

아래의 블로그에 가면 MacOS에서 아주 쉽게 적용 가능한 방법을 소개해준다.

https://blog.godatadriven.com/black-formatting-selection


위의 설명대로 세팅한 뒤, 코드의 일부만 드래그해서 선택하고 partial black을 실행하면 된다.


그런데 WindowOS를 사용하는 나와 같은 사람은 위 방법을 쓸 수가 없다. 왜냐하면 sh파일은 윈도우 운영체제가 바로 실행시킬 수 없는 프로그램이기 때문이다. 따라서 python으로 위의 partial black을 다시 코딩한 뒤 이를 auto-py-to-exe 를 사용하여 exe파일로 컴파일 시킨 다음 PyCharm에 등록하여 사용하는 방법을 만들었다.


Windows에서 Partial Black 사용하기

내가 작성한 파이썬 코드는 다음과 같다.

https://gist.github.com/imcomking/04d8ce30b6ac444e413392ab675b1d2c


"""
It is partial black in python to be utilized in windows PyCharm.
- To see partial black here (https://blog.godatadriven.com/black-formatting-selection)
- This code is conversion of this shell script (https://gist.github.com/BasPH/5e665273d5e4cb8a8eefb6f9d43b0b6d)

If you want to use in windows, you should first complie this python to exe.
- To do that, see (https://pypi.org/project/auto-py-to-exe/)
"""
import os
import sys
import tempfile

print("The arguments are: ", str(sys.argv))

# get the system argv
_partial_black = sys.argv[0]
black = sys.argv[1]
input_file = sys.argv[2]
start_line = int(sys.argv[3])-1
end_line = int(sys.argv[4])

# read input_file
with open(input_file, "rt", encoding="utf-8") as src_file:
src_contents = [line for line in src_file]
selection = src_contents[start_line:end_line]

print("Total file len: ", len(src_contents), "selected lines:", len(selection))

# it is a workaround for escaping windows os permission problem.
tmp_dir = tempfile.TemporaryDirectory()
tmp_file_name = os.path.join(tmp_dir.name, 'tmp_file_for_black')

# write selection on tmp_file
with open(tmp_file_name, "wt", encoding="utf-8") as f:
f.writelines(selection)

# run black on tmp_file
cmd = black+" "+tmp_file_name
print("Run cmd:", cmd)
os.system(cmd)

# apply reformatted selection to origianl source file
with open(tmp_file_name, "rt", encoding="utf-8") as f:
del src_contents[start_line:end_line]
for i, line in enumerate(f):
src_contents.insert(start_line+i, line)

# overwrite it to input_file
with open(input_file, "wt", encoding="utf-8") as f:
f.writelines(src_contents)


이 코드를 다운 받은 다음, https://pypi.org/project/auto-py-to-exe/ 을 설치하고 이를 이용하여 exe로 컴파일한다.

https://newsight.tistory.com/315


컴파일된 exe는 여기에 있다.

https://www.dropbox.com/s/eacz7kf28l7q6sr/output.zip?dl=0



그 다음 PyCharm에 external tool로 등록시켜준다.


Pycharm에서 File-Setting-Tools-External Tools에서 추가버튼 누르고, 다음을 입력


Name: partial Black

Description: It is partial formatting version of Black.

Program: <컴파일한 partial_black.exe파일의 경로>

Arguments: <일반 black.exe파일의 경로> "$FilePath$" $SelectionStartLine$ $SelectionEndLine$

Working directory: <Anaconda3 Scripts폴더의 경로>


사용법: Tools - External Tools - black 클릭
또는 아래와 같이 단축키 등록을 한다.





위의 과정에 대한 step-by-step 문서를 영어로 작성하였다.




'Development > Python' 카테고리의 다른 글

Advanced Python Scheduler  (0) 2020.02.18
Airflow  (0) 2020.02.11
Python 파일을 exe파일로 컴파일하기  (0) 2020.02.04
Python Concurrency Programming  (4) 2020.01.09
Python 프로젝트 배포 및 다른 패키지 가져오기  (2) 2020.01.09

댓글