[Snippet] 자주쓰는 Python 코드

jongmin-oh·2023년 4월 25일
0

GPU 선택

CUDA_VISIBLE_DEVICES=2 python train.py

#jupyter
import os

os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"  # Arrange GPU devices starting from 0
os.environ["CUDA_VISIBLE_DEVICES"]= "1"

디렉터리가 없으면 생성

import os

if not os.path.exists("path"):
    os.makedirs("path")

2차원 리스트를 1차원으로 변경

import itertools

list2 = list(itertools.chain(*list1))

현재 날짜 파일명에 추가

from datetime import datetime

f"파일명_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}"

파일 경로 연결

from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent

os.path.join(TRAIN_DATA_PATH, name)

BASE_DIR: Path = Path(__file__).resolve().parent.parent
MODEL_DIR: Path = BASE_DIR.joinpath("models")
LOGS_DIR: Path = BASE_DIR.joinpath("logs")

ONNX_DIR: Path = MODEL_DIR.joinpath("onnx")
FAISS_DIR: Path = MODEL_DIR.joinpath("faiss")

Json 내보내기

with open(BASE_DIR + f"/result/전체메신저.json", "w", encoding='utf-8') as json_file:
    json.dump(total_dict, json_file, ensure_ascii=False, indent='\t')

Json 불러오기

json.load(open("request_data.json", "r", encoding="utf-8"))

Json(Dict) 깔끔하게 보이게하기

import json
print(json.dumps(result, indent=2, sort_keys=True, ensure_ascii=False))

txt 파일 읽기

example = [line.strip() for line in open('example.txt', 'r')]

txt 파일 쓰기(리스트 요소별로 한줄씩)

my_list = ["첫 번째 줄", "두 번째 줄", "세 번째 줄"]

with open("my_file.txt", "w") as f:
    for item in my_list:
        f.write("%s\n" % item)

.env 파라미터 불러오기

from dotenv import load_dotenv

load_dotenv(".env")

URL = os.getenv("URL")

Sington Pattern

class Singleton(type):
    instance = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls.instance:
            cls.instance[cls] = super().__call__(*args, **kwargs)
        return cls.instance[cls]
profile
Technical Problem Solver (기술로 문제를 해결하는 사람)

0개의 댓글