파이썬 체크시트

자주 사용되는 파이썬 코드 조각

Page content

가끔은 필요하지만 바로 찾기 어려운 경우가 있습니다.
그래서 모두 여기에 모아두었습니다.

이것들은 새로운 것이 아니라,
단지 복사 붙여넣기 한 것들일 뿐이지만,
저에게는 작동하고,
혹시 여러분에게도 유용하게 사용될 수 있기를 바랍니다.

Awesome Python in 3d

일반적인 Anaconda 명령

Conda가 설치되어 있는지 확인

conda -V

Conda가 최신 상태인지 확인

conda update conda

가상 환경을 생성

conda create -n newenvname python=3.12 anaconda

가상 환경을 활성화

source activate newenvname

가상 환경에 추가적인 Python 패키지를 설치

conda install -n newenvname [package]

가상 환경을 비활성화

source deactivate

가상 환경을 삭제

conda remove -n newenvname --all

프로그램 의존성

의존성 설치 - requirements 파일 사용

패키지를 개별적으로 설치하는 대신, pip는 모든 의존성을 requirements 파일에 선언할 수 있습니다. 예를 들어, requirements.txt 파일을 생성하여 다음과 같이 작성할 수 있습니다:

requests==2.18.4
google-auth==1.1.0

그리고 pip에게 이 파일에 있는 모든 패키지를 설치하도록 지시할 수 있습니다:

python3 -m pip install -r requirements.txt

의존성 동결

pip는 freeze 명령을 사용하여 설치된 모든 패키지와 버전 목록을 내보낼 수 있습니다:

python3 -m pip freeze

이 명령은 다음과 같은 결과를 출력합니다:

requests==2.18.4
google-auth==1.1.0

pip freeze 명령은 환경에 설치된 모든 패키지의 정확한 버전을 다시 생성할 수 있는 requirements 파일을 만들 때 유용합니다.

직사각형 그리기

import cv2

cv2.rectangle(img, (x1, y1), (x2, y2), color=(255,0,0), thickness=2)

x1,y1 ------
|          |
|          |
|          |
--------x2,y2

다음 코드를 추가하여 질문을 계속할 수 있습니다:

cv2.imwrite("my.png",img)

cv2.imshow("lalala", img)
k = cv2.waitKey(0) # 0==wait forever

PIL Image 객체가 있고, 이 이미지에 직사각형을 그릴 수 있습니다. OpenCV2를 사용하여 직사각형을 그린 후 다시 PIL Image 객체로 변환하고 싶다면 다음과 같이 수행할 수 있습니다:

# im은 PIL Image 객체입니다.
im_arr = np.asarray(im)
# RGB 배열을 OpenCV의 BGR 형식으로 변환
im_arr_bgr = cv2.cvtColor(im_arr, cv2.COLOR_RGB2BGR)
# pts1과 pts2는 직사각형의 좌상단과 우하단 좌표입니다.
cv2.rectangle(im_arr_bgr, pts1, pts2,
              color=(0, 255, 0), thickness=3)
im_arr = cv2.cvtColor(im_arr_bgr, cv2.COLOR_BGR2RGB)
# 다시 Image 객체로 변환
im = Image.fromarray(im_arr)

간단한 인자 파싱

import json

#---------------------------------------------------------------------------
def do_some_awesomeness(src_file, tgt_file):
    print('Converting some stuff from {} to {}'.format(src_file, tgt_file))

#---------------------------------------------------------------------------
def run():
    import argparse

    parser = argparse.ArgumentParser(description="Some mega useful and efficient python tool.")
    parser.add_argument("-s", "--src", dest="src_file",
        help="input json filename")
    parser.add_argument("-t", "--tgt", dest="tgt_file",
        help="output json filename")
    
    args = parser.parse_args()

    do_some_awesomeness(args.src_file, args.tgt_file)

if __name__ == '__main__':
    run()

이렇게 호출할 수 있습니다:

python ave_roma.py --src 1.json --tgt 2.json

JSON 로드 및 저장

import json

def do_convert(src_file, tgt_file):

    with open(src_file) as f:
        src = json.load(f)

    tgt = src # :)

    with open(tgt_file, 'w', encoding='utf-8') as f:
        json.dump(tgt, f, ensure_ascii=False, indent=4)

확장자 없는 파일명 얻기

import os

print(os.path.splitext("/path/to/some/file.txt")[0])

이 코드는 다음과 같이 출력됩니다:

/path/to/some/file

유용한 링크