Timeout(): 실제 사례

Python으로 함수 작성하기

Shayne Miel

Software Architect @ Duo Security

타임아웃


def function1():
  # 이 함수는 가끔
  # 매우 오래 실행됩니다
  ...

def function2(): # 이 함수는 가끔 # 멈추고 반환하지 않습니다 ...
Python으로 함수 작성하기

타임아웃

@timeout
def function1():
  # 이 함수는 가끔
  # 매우 오래 실행됩니다
  ...

@timeout def function2(): # 이 함수는 가끔 # 멈추고 반환하지 않습니다 ...

스톱워치

Python으로 함수 작성하기

타임아웃 - 배경 지식

import signal

def raise_timeout(*args, **kwargs): raise TimeoutError()
# "알람" 시그널이 오면 raise_timeout() 호출 signal.signal(signalnum=signal.SIGALRM, handler=raise_timeout)
# 5초 후 알람 설정 signal.alarm(5)
# 알람 취소 signal.alarm(0)
Python으로 함수 작성하기
def timeout_in_5s(func):

@wraps(func) def wrapper(*args, **kwargs):
# 5초 알람 설정 signal.alarm(5)
try: # 데코레이트된 함수 호출 return func(*args, **kwargs)
finally: # 알람 취소 signal.alarm(0)
return wrapper
@timeout_in_5s
def foo():
  time.sleep(10)
  print('foo!')
foo()
TimeoutError
Python으로 함수 작성하기
def timeout(n_seconds):

def decorator(func):
@wraps(func) def wrapper(*args, **kwargs):
# n초 후 알람 설정 signal.alarm(n_seconds)
try: # 데코레이트된 함수 호출 return func(*args, **kwargs) finally: # 알람 취소 signal.alarm(0)
return wrapper
return decorator
@timeout(5)
def foo():
  time.sleep(10)
  print('foo!')

@timeout(20) def bar(): time.sleep(10) print('bar!')
foo()
TimeoutError
bar()
bar!
Python으로 함수 작성하기

Let's practice!

Python으로 함수 작성하기

Preparing Video For Download...