| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | |||||
| 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| 10 | 11 | 12 | 13 | 14 | 15 | 16 |
| 17 | 18 | 19 | 20 | 21 | 22 | 23 |
| 24 | 25 | 26 | 27 | 28 | 29 | 30 |
| 31 |
- 명령어
- 오류
- C#
- C
- Python
- JSON
- 컨테이너
- nvidia-smi
- Linux
- pytorch
- YOLO
- Visual Studio
- 기타 연주
- Docker
- 프로그래머스
- OpenCV
- SSH
- VS Code
- label
- 채보
- pip
- Selenium
- C++
- ubuntu
- paramiko
- error
- pandas
- Numpy
- windows forms
- mysql
- Today
- Total
목록Python (108)
기계는 거짓말하지 않는다
Python에서 실행 파일에 option을 전달할 때 argparse를 자주 사용한다.예를 들어 학습 코드에서 GPU 사용 여부, 저장 여부, debug mode 등을 command line argument로 받는 경우가 많다.python train.py --use_gpu --save_model이때 boolean 값을 받기 위해 아래처럼 작성하는 경우가 있다.import argparseparser = argparse.ArgumentParser()parser.add_argument("--use_gpu", type=bool)args = parser.parse_args()print(args.use_gpu)하지만 type=bool은 의도와 다르게 동작할 수 있다.1. type=bool 문제아래 코드를 실행한다고..
Python의 tracemalloc은 코드에서 메모리 할당을 추적할 수 있도록 도와주는 기본 모듈이다.가장 많은 메모리를 할당하는 5개의 파일을 표시한 출력 형식은 아래와 비슷하다./home/user/test.py:1817: size=18.2 MiB, count=556, average=33.5 KiB:672: size=438 KiB, count=4584, average=98 B/usr/lib/python3.10/threading.py:258: size=417 KiB, count=1384, average=309 B:241: size=175 KiB, count=1871, average=96 B/usr/lib/python3.10/queue.py:207: size=144 KiB, count=467, averag..
Python의 faulthandler 모듈은 프로그램에서 발생하는 심각한 오류나예외(메모리 관련 오류)에 대한 진단을 돕는 모듈이다.Python의 내부 오류나 C 확장 모듈에서 발생한 오류를 추적하고,문제가 발생한 지점을 더 쉽게 찾아내도록 도와준다.Python 3.3 버전 이상에서만 사용할 수 있다.기본 사용법은 아래와 같다.import faulthandlerfaulthandler.enable()심각한 오류 발생 시 자동으로 스택 트레이스를 출력하여 문제 발생 지점을 알려준다.코드 실행 중 특정 지점에서 수동으로 스택 트레이스를 출력하려면 dump_traceback을 사용할 수 있다.import faulthandlerfaulthandler.dump_traceback()faulthandler — 파이썬 ..
Python에서 colorsys 모듈을 이용하여 지정된 개수만큼의 색상을일정하게 분포된 색상 팔레트를 생성하는 간단한 함수이다.import colorsysdef generate_colors(num_classes: int, alpha=1): """ list of tuple: (R, G, B, A) 0~255 """ colors = [] for i in range(num_classes): hue = i / num_classes # S=1.0, V=1.0 rgb = colorsys.hsv_to_rgb(hue, 1.0, 1.0) # # RGB 0~255 # r, g, b = [int(x * 255) for x in ..
Python의 configparser 모듈로 config file을 읽고 쓰면 config file의 주석은 유지되지 않는다.주석을 유지해야 할 때, 가능하도록 간단히 구현한 예시이다.import configparserdef read_config_with_comments(file_path): """config file과 config file의 line을 함께 read""" with open(file_path, 'r') as file: lines = file.readlines() config = configparser.ConfigParser(allow_no_value=True) config.read(file_path) return config, lines ..
Python에서 파일을 열 때 사용하는 open 함수의 mode 매개변수에 관한 간략한 설명이다.mode 매개변수는 파일을 어떤 방식으로 열지 결정하고, 이에 따라 파일 읽기, 쓰기, 추가를 할 수 있다.텍스트 모드, 바이너리 모드를 선택할 수 있다.기본 모드는 t(text mode), 텍스트 모드이다.모드 종류, 요약r / r+: 읽기 전용 / 읽기 및 쓰기 w / w+: 쓰기 전용 (기존 내용 삭제) / 쓰기 및 읽기 (기존 내용 삭제) a / a+: 추가 모드 / 추가 및 읽기 모드 b: 바이너리 모드 (위 모드와 결합 가능) x: 배타적 생성 모드 (파일이 존재하지 않을 때만 생성)모드 설명r (읽기 전용)파일을 읽기 전용으로 연다.파일이 존재하지 않으면 FileNotFoundError 예외가 발..
Python의 paramiko 모듈을 이용하여 원격 서버에 SSH 접속 후,passwd와 같이 명령어를 여러 번 주고받아야 할 경우에 간단하게 사용할 수 있는 방법이다.import paramikoimport timedef instance_change_password(function_args: dict): ''' args server_ip, user_name, server_password, new_password ''' client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(function_args['server_ip'],..
Python logging 모듈의 logger를 설정하는 간단한 예제 함수 코드이다.경로와 loglevel은 필요에 따라 수정하면 된다.import loggingimport datetimeimport osdef setup_logger(log_file_name = "proccess.log", log_name = "logger", log_dir_root_path = "./logs"): current_date = datetime.datetime.now().strftime("%Y%m%d") log_dir = f"{log_dir_root_path}/{current_date}" os.makedirs(log_dir, exist_ok=True) # log file path setting ..