파이썬 time.sleep(): 코드에 지연 추가하는 방법 (예제)
파이썬 time.sleep(): 코드에 지연 추가하는 방법 (예제)
파이썬 Sleep이란?
time.sleep() 함수는 파이썬 스크립트 실행을 지정된 초만큼 일시 정지합니다. 표준 time 모듈의 일부로, 외부 프로세스 대기, 지연 시뮬레이션, 출력 지연 등에 유용합니다.
이 가이드에서 배울 내용:
time.sleep() 작동 원리와 문법
time.sleep() 실용 예제
- 함수 실행 지연 방법
- 대체 지연 방법:
asyncio.sleep(), Event().wait(), Timer
문법
import time
# seconds 초 동안 일시 정지
# 예: time.sleep(5) # 5초 정지
매개변수
seconds – 프로그램이 일시 정지할 초 수를 나타내는 실수 또는 정수. 초 단위 미만도 지원.
예제: time.sleep() 기본 사용
다음 단계로 지연 동작 확인:
import time
- 일시 정지하려는 위치에
time.sleep(5) 추가.
import time
print("Welcome to Python Tutorials")
time.sleep(5)
print("이 메시지는 5초 뒤 나타납니다")
출력 (5초 후):
Welcome to Python Tutorials
이 메시지는 5초 뒤 나타납니다
함수 호출 지연
함수 실행 전 지연이 필요할 때 time.sleep()을 함수 호출 앞에 배치:
import time
print('실행 시작')
def display():
print('Welcome to Python Tutorials')
time.sleep(5)
display()
print('지연 후 함수 실행됨')
출력 (5초 후):
실행 시작
Welcome to Python Tutorials
지연 후 함수 실행됨
지연 도입의 다른 방법들
1. 루프에서 time.sleep() 사용
문자열 각 문자를 1초 간격으로 출력:
import time
message = "Guru99"
for char in message:
print(char)
time.sleep(1)
2. asyncio.sleep()으로 비동기 지연
파이썬 3.4부터 asyncio.sleep()으로 논블로킹 지연 가능:
import asyncio
print('비동기 실행 시작')
async def display():
await asyncio.sleep(5)
print('Welcome to Python Tutorials')
asyncio.run(display())
3. 스레딩 Event Wait
Event().wait() 메서드로 지정된 초만큼 실행 정지:
from threading import Event
print('Event 대기 시작')
def display():
print('Welcome to Python Tutorials')
Event().wait(5)
display()
4. 스레딩 Timer
Timer로 지연 후 함수 실행 예약:
from threading import Timer
print('Timer 시작')
def display():
print('Welcome to Python Tutorials')
Timer(5, display).start()
핵심 요약
- 정확한 시간 동안 실행을 일시 정지하려면
time.sleep() 사용.
- 비동기 코드에서 논블로킹 지연 필요 시
asyncio.sleep() 사용.
Event().wait(), Timer 같은 스레딩 도구로 대체 지연 메커니즘 제공.
- 애플리케이션의 동시성 모델에 가장 적합한 방법 선택.