[cheatsheet] python

boychaboy·2023년 6월 9일
0

personal cheatsheet

목록 보기
4/7

time

import time

# 현재 시간을 초 단위로 가져온다.
current_time_seconds = time.time()

# 초 단위의 시간을 struct_time 객체로 변환한다.
local_time = time.localtime(current_time_seconds)

# struct_time 객체를 원하는 문자열 형식으로 포맷한다.
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time)

print(formatted_time)

textwrap

from textwrap import dedent

def some_function():
    text = """
        여러 줄의
        텍스트가
        여기 있습니다.
    """
    print(text)

위 코드에서 text 변수에 저장된 문자열은 각 줄 앞에 추가적인 공백이 포함될 것입니다. 이 공백은 문자열이 함수 내에서 들여쓰기 되었기 때문에 생깁니다. textwrap.dedent() 함수를 사용하면 이러한 추가적인 공백을 제거할 수 있습니다

Dictionary one-line (딕셔너리 한 줄 작성)

temp = ["오늘", "밥", "먹다", "밥"]
temp_dict = {idx: word for idx, word in enumerate(temp)}

print(temp_dict)

# > {0: '오늘', 1: '밥', 2: '먹다', 3: '밥'}

Formatting (포매팅)

  • f-string으로 포매팅 하는 방법

자리수

  • 정수: f"{:N}"
    - N 앞에 0을 붙이면 빈 부분을 0으로 채워줌
  • 소수점: f"{:.Mf}"
  • 전체: f{:N.Mf}"
pi = 3.1416
print(f'소수점 두자리 : {pi:.2f}')
# > 소수점 두자리 : 3.14

print(f'10칸 공백 채움 소수점 두자리 : {pi:10.2f}')
# > 10칸 공백 채움 소수점 두자리 :       3.14

print(f'10칸 0 채움 소수점 두자리 : {pi:010.2f}')
# > 10칸 0 채움 소수점 두자리 : 0000003.14

정렬

  • 왼쪽: {:<N}
  • 가운데: {:^N}
  • 오른쪽: {:>N}
# 왼쪽 정렬
s1 = 'left'
print(f'|{s1:<10}|')

 
# 가운데 정렬
s2 = 'mid'
result2 = f'|{s2:^10}|'
print(result2)
 
# 오른쪽 정렬
s3 = 'right'
result3 = f'|{s3:>10}|'
print(result3)

# >
# |left      |
# |   mid    |
# |     right|

Multiprocessing (멀티프로세싱)

  1. multiprocessing.process로 프로세스를 생성한다.
  2. target으로는 작업을 수행할 함수를, args으로는 함수로 전달할 인자를 지정한다.
  3. p.start() 명령어로 해당 프로세스를 가동시킨다.
  4. p.join() 명령어로 해당 프로세스가 종료되기를 기다린다.
  • CPU의 개수는 os.cpu_count() 명령어로 확인이 가능하다.
import time


def heavy_work(name):
    result = 0
    for i in range(4000000):
        result += i
    print('%s done' % name)


if __name__ == '__main__':
    import multiprocessing
    import os

	# CPU 개수 확인
    num_cpu = os.cpu_count()
    start = time.time()
    procs = []
    for i in range(num_cpu):
        p = multiprocessing.Process(target=heavy_work, args=(i, ))
        p.start()
        procs.append(p)

    for p in procs:
        p.join()  # 프로세스가 모두 종료될 때까지 대기

    end = time.time()

    print("수행시간: %f 초" % (end - start))

리턴 값이 있는 경우

import multiprocessing


def worker(procnum, return_dict):
    """worker function"""
    print(str(procnum) + " represent!")
    return_dict[procnum] = procnum


if __name__ == "__main__":
    manager = multiprocessing.Manager()
    return_dict = manager.dict()
    jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=worker, args=(i, return_dict))
        jobs.append(p)
        p.start()

    for proc in jobs:
        proc.join()
    print(return_dict.values())

Progress Bar 를 표시하고 싶은 경우

import parmap
from multiprocessing import Manager

num_cores = 4 # 사용할 cpu 코어 수. multiprocessing.cpu_count() 로 확인 가능
manager = Manager()
d = manager.dict()

def a(x, d):
    d[x] = 1

input_list = range(0, 4)
parmap.map(a, input_list, d, pm_pbar=True, pm_processes=num_cores)

현재 경로를 가져와서 디렉토리 생성하기

os.getcwd()

  • 지금 작업하고 있는 파일의 경로를 반환
import os
current_path = os.getcwd()
print("현재 위치 : " + current_path)

# 현재 위치 : /Users/younghoon/Codes

os.makedir

  • 현재 경로에 폴더를 생성
  • 입력한 경로가 존재하지 않거나, 같은 폴더가 이미 존재하는 경우 에러 발생
import os
os.mkdir('./new_folder')

os.makedirs

  • 현재 경로에 폴더를 "원하는 만큼" 생성
  • exist_ok=True: 폴더가 존재하는 경우 생성하지 않고, 에러도 발생시키지 않음
import os
os.makedirs('./a/b/c', exist_ok=True)

디렉토리 파일 리스트 가져오기

os.listdir

import os

pwd = os.getcwd()
file_list = os.listdir(pwd)

glob.glob

import glob

pwd = "./*"
file_list = glob.glob(path)

Python .gitignore

Python Error Types and Explanations

ExceptionDescription
AssertionErrorRaised when the assert statement fails.
AttributeErrorRaised on the attribute assignment or reference fails.
EOFErrorRaised when the input() function hits the end-of-file condition.
FloatingPointErrorRaised when a floating point operation fails.
GeneratorExitRaised when a generator's close() method is called.
ImportErrorRaised when the imported module is not found.
IndexErrorRaised when the index of a sequence is out of range.
KeyErrorRaised when a key is not found in a dictionary.
KeyboardInterruptRaised when the user hits the interrupt key (Ctrl+c or delete).
MemoryErrorRaised when an operation runs out of memory.
NameErrorRaised when a variable is not found in the local or global scope.
NotImplementedErrorRaised by abstract methods.
OSErrorRaised when a system operation causes a system-related error.
OverflowErrorRaised when the result of an arithmetic operation is too large to be represented.
ReferenceErrorRaised when a weak reference proxy is used to access a garbage collected referent.
RuntimeErrorRaised when an error does not fall under any other category.
StopIterationRaised by the next() function to indicate that there is no further item to be returned by the iterator.
SyntaxErrorRaised by the parser when a syntax error is encountered.
IndentationErrorRaised when there is an incorrect indentation.
TabErrorRaised when the indentation consists of inconsistent tabs and spaces.
SystemErrorRaised when the interpreter detects internal error.
SystemExitRaised by the sys.exit() function.
TypeErrorRaised when a function or operation is applied to an object of an incorrect type.
UnboundLocalErrorRaised when a reference is made to a local variable in a function or method, but no value has been bound to that variable.
UnicodeErrorRaised when a Unicode-related encoding or decoding error occurs.
UnicodeEncodeErrorRaised when a Unicode-related error occurs during encoding.
UnicodeDecodeErrorRaised when a Unicode-related error occurs during decoding.
UnicodeTranslateErrorRaised when a Unicode-related error occurs during translation.
ValueErrorRaised when a function gets an argument of correct type but improper value.
ZeroDivisionErrorRaised when the second operand of a division or module operation is zero.

Python Docstring Example

def string_reverse(str1: str) -> str:
    """
    Returns the reversed String.

    Args:
        str1 (str): The string which is to be reversed.

    Returns:
        reverse (str): The string which gets reversed.

    Todo:
        * eat breakfast
    """

    reverse_str1 = ''
    i = len(str1)
    while i > 0:
        reverse_str1 += str1[i - 1]
        i = i- 1
    return reverse_str1
profile
no vim no code

0개의 댓글