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)
from textwrap import dedent
def some_function():
text = """
여러 줄의
텍스트가
여기 있습니다.
"""
print(text)
위 코드에서 text 변수에 저장된 문자열은 각 줄 앞에 추가적인 공백이 포함될 것입니다. 이 공백은 문자열이 함수 내에서 들여쓰기 되었기 때문에 생깁니다. textwrap.dedent() 함수를 사용하면 이러한 추가적인 공백을 제거할 수 있습니다
temp = ["오늘", "밥", "먹다", "밥"]
temp_dict = {idx: word for idx, word in enumerate(temp)}
print(temp_dict)
# > {0: '오늘', 1: '밥', 2: '먹다', 3: '밥'}
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.process
로 프로세스를 생성한다. target
으로는 작업을 수행할 함수를, args
으로는 함수로 전달할 인자를 지정한다. p.start()
명령어로 해당 프로세스를 가동시킨다. 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)
.gitignore
Exception | Description |
---|---|
AssertionError | Raised when the assert statement fails. |
AttributeError | Raised on the attribute assignment or reference fails. |
EOFError | Raised when the input() function hits the end-of-file condition. |
FloatingPointError | Raised when a floating point operation fails. |
GeneratorExit | Raised when a generator's close() method is called. |
ImportError | Raised when the imported module is not found. |
IndexError | Raised when the index of a sequence is out of range. |
KeyError | Raised when a key is not found in a dictionary. |
KeyboardInterrupt | Raised when the user hits the interrupt key (Ctrl+c or delete). |
MemoryError | Raised when an operation runs out of memory. |
NameError | Raised when a variable is not found in the local or global scope. |
NotImplementedError | Raised by abstract methods. |
OSError | Raised when a system operation causes a system-related error. |
OverflowError | Raised when the result of an arithmetic operation is too large to be represented. |
ReferenceError | Raised when a weak reference proxy is used to access a garbage collected referent. |
RuntimeError | Raised when an error does not fall under any other category. |
StopIteration | Raised by the next() function to indicate that there is no further item to be returned by the iterator. |
SyntaxError | Raised by the parser when a syntax error is encountered. |
IndentationError | Raised when there is an incorrect indentation. |
TabError | Raised when the indentation consists of inconsistent tabs and spaces. |
SystemError | Raised when the interpreter detects internal error. |
SystemExit | Raised by the sys.exit() function. |
TypeError | Raised when a function or operation is applied to an object of an incorrect type. |
UnboundLocalError | Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable. |
UnicodeError | Raised when a Unicode-related encoding or decoding error occurs. |
UnicodeEncodeError | Raised when a Unicode-related error occurs during encoding. |
UnicodeDecodeError | Raised when a Unicode-related error occurs during decoding. |
UnicodeTranslateError | Raised when a Unicode-related error occurs during translation. |
ValueError | Raised when a function gets an argument of correct type but improper value. |
ZeroDivisionError | Raised when the second operand of a division or module operation is zero. |
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