Programing

Python에서 어떻게 시간 지연을 할 수 있을까?

c10106 2022. 4. 4. 19:28
반응형

Python에서 어떻게 시간 지연을 할 수 있을까?

나는 파이톤 스크립트에 시간 지연을 넣는 방법을 알고 싶다.

import time
time.sleep(5)   # Delays for 5 seconds. You can also use a float value.

1분에 한 번 정도 실행되는 다른 예는 다음과 같다.

import time
while True:
    print("This prints once a minute.")
    time.sleep(60) # Delay for 1 minute (60 seconds).

모듈에서 그 기능을 사용할 수 있다.그것은 2초 미만의 해상도를 위해 부동의 논거를 취할 수 있다.

from time import sleep
sleep(0.1) # Time in seconds

Python에서 어떻게 시간 지연을 할 수 있을까?

하나의 나사산에서 나는 수면 기능을 제안한다.

>>> from time import sleep

>>> sleep(4)

이 함수는 실제로 운영체제에 의해 호출되는 스레드의 처리를 중지시켜 다른 스레드와 프로세스가 수면 중에 실행되도록 한다.

이러한 목적으로 사용하거나, 단순히 함수의 실행을 지연시키기 위해 사용하십시오.예를 들면 다음과 같다.

>>> def party_time():
...     print('hooray!')
...
>>> sleep(3); party_time()
hooray!

"hooray!"는 내가 치고 3초 후에 인쇄된다.

예제 사용sleep여러 개의 스레드 및 프로세스 사용

또.sleep스레드를 중단한다 - 처리 능력이 제로인 것 옆에 사용한다.

시연하려면 다음과 같은 스크립트를 작성하십시오(처음 대화형 Python 3.5 쉘에서 시도했지만 하위 프로세스는 해당 스크립트를 찾을 수 없음).party_later어떤 이유로 기능한다:

from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
from time import sleep, time

def party_later(kind='', n=''):
    sleep(3)
    return kind + n + ' party time!: ' + __name__

def main():
    with ProcessPoolExecutor() as proc_executor:
        with ThreadPoolExecutor() as thread_executor:
            start_time = time()
            proc_future1 = proc_executor.submit(party_later, kind='proc', n='1')
            proc_future2 = proc_executor.submit(party_later, kind='proc', n='2')
            thread_future1 = thread_executor.submit(party_later, kind='thread', n='1')
            thread_future2 = thread_executor.submit(party_later, kind='thread', n='2')
            for f in as_completed([
              proc_future1, proc_future2, thread_future1, thread_future2,]):
                print(f.result())
            end_time = time()
    print('total time to execute four 3-sec functions:', end_time - start_time)

if __name__ == '__main__':
    main()

이 스크립트의 출력 예:

thread1 party time!: __main__
thread2 party time!: __main__
proc1 party time!: __mp_main__
proc2 party time!: __mp_main__
total time to execute four 3-sec functions: 3.4519670009613037

멀티스레딩

를 가진 별도의 스레드에서 나중에 호출할 함수를 트리거할 수 있다.Timer 스레딩 객체:

>>> from threading import Timer
>>> t = Timer(3, party_time, args=None, kwargs=None)
>>> t.start()
>>>
>>> hooray!

>>>

빈 라인은 표준 출력물에 인쇄된 함수를 보여주고 있으며, 나는 프롬프트에 표시되도록 하기 위해 때려야 했다.

이 방법의 거꾸로 된 것은, 반면, 이 방법의 위상은, 그 동안에.Timer스레드가 기다리고 있었고, 나는 이 경우, 함수가 실행되기 전에 한 번 때리는 다른 일을 할 수 있었다(첫 번째 빈 프롬프트 참조).

다중 처리 라이브러리에 각 개체가 없음당신은 하나를 만들 수 있지만, 그것은 아마도 이유 때문에 존재하지 않을 것이다.하위 스레드는 완전히 새로운 하위 프로세스보다 단순한 타이머에 훨씬 더 적합하다.

지연은 다음과 같은 방법으로도 실시할 수 있다.

첫 번째 방법:

import time
time.sleep(5) # Delay for 5 seconds.

두 번째 지연 방법은 다음과 같은 암묵적 대기 방법을 사용하는 것이다.

 driver.implicitly_wait(5)

세 번째 방법은 특정 작업이 완료될 때까지 또는 요소가 발견될 때까지 기다려야 할 때 더 유용하다.

self.wait.until(EC.presence_of_element_located((By.ID, 'UserName'))

내가 아는 다섯 가지 방법이 있다.time.sleep() pygame.time.wait(), matplotlib의pyplot.pause() .after()그리고asyncio.sleep().


time.sleep()예제(tkinter를 사용할 경우 사용하지 않음):

import time
print('Hello')
time.sleep(5) # Number of seconds
print('Bye')

pygame.time.wait()예(피게임 윈도우를 사용하지 않는 경우 권장되지 않지만 즉시 윈도우를 종료할 수 있음):

import pygame
# If you are going to use the time module
# don't do "from pygame import *"
pygame.init()
print('Hello')
pygame.time.wait(5000) # Milliseconds
print('Bye')

매플리트립의 함수pyplot.pause()예제(그래프를 사용하지 않는 경우 권장되지 않지만 즉시 그래프를 종료할 수 있음):

import matplotlib
print('Hello')
matplotlib.pyplot.pause(5) # Seconds
print('Bye')

.after() 잘 어울림방법(Tkinter와 가 가 어 어 어):):

import tkinter as tk # Tkinter for Python 2
root = tk.Tk()
print('Hello')
def ohhi():
    print('Oh, hi!')
root.after(5000, ohhi) # Milliseconds and then a function
print('Bye')

마침내, 더asyncio.sleep()방법:

import asyncio
asyncio.sleep(5)

졸린 발전기랑 재미 좀 보자고

문제는 시간 지연에 관한 것이다.정해진 시간은 될 수 있지만, 지난번 이후로 측정된 지연이 필요할 수도 있어.한 가지 가능한 해결책이 있다.

지난 시간 이후 측정된 지연(정기적으로 웨이크업)

상황이 그럴 수도 있고, 우리는 가능한 한 정기적으로 무언가를 하고 싶고, 모든 일에 신경 쓰고 싶지 않다.last_time next_time우리 암호에 모든 걸 걸다

부저 발전기

다음 코드(sleepy.py)는 다음을 정의한다.buzzergen제너레이터:

import time
from itertools import count

def buzzergen(period):
    nexttime = time.time() + period
    for i in count():
        now = time.time()
        tosleep = nexttime - now
        if tosleep > 0:
            time.sleep(tosleep)
            nexttime += period
        else:
            nexttime = now + period
        yield i, nexttime

일반 부저겐 호출

from sleepy import buzzergen
import time
buzzer = buzzergen(3) # Planning to wake up each 3 seconds
print time.time()
buzzer.next()
print time.time()
time.sleep(2)
buzzer.next()
print time.time()
time.sleep(5) # Sleeping a bit longer than usually
buzzer.next()
print time.time()
buzzer.next()
print time.time()

그리고 그것을 실행하면 다음과 같은 것을 볼 수 있다.

1400102636.46
1400102639.46
1400102642.46
1400102647.47
1400102650.47

우리는 또한 루프로 직접 사용할 수 있다.

import random
for ring in buzzergen(3):
    print "now", time.time()
    print "ring", ring
    time.sleep(random.choice([0, 2, 4, 6]))

그리고 실행하면 다음과 같은 것을 볼 수 있을 것이다.

now 1400102751.46
ring (0, 1400102754.461676)
now 1400102754.46
ring (1, 1400102757.461676)
now 1400102757.46
ring (2, 1400102760.461676)
now 1400102760.46
ring (3, 1400102763.461676)
now 1400102766.47
ring (4, 1400102769.47115)
now 1400102769.47
ring (5, 1400102772.47115)
now 1400102772.47
ring (6, 1400102775.47115)
now 1400102775.47
ring (7, 1400102778.47115)

보시다시피 이 버저가 너무 경직되지 않아 늦잠을 자고 규칙적인 일정에서 벗어나도 규칙적인 졸음 간격을 따라잡을 수 있다.

파이톤 표준 라이브러리의 Tkinter 라이브러리는 당신이 가져올 수 있는 인터랙티브 도구다.기본적으로, 당신은 당신이 코드로 조작하는 창으로 보이는 버튼과 상자, 팝업과 것들을 만들 수 있다.

만약 당신이 TKinter를 사용한다면, 그것은 당신의 프로그램을 망칠 것이기 때문에 Tkinter를 사용하지 마십시오.이런 일이 내게 일어났다.대신, 사용root.after()몇 초 동안 밀리초 단위로 값을 교체하십시오.예를 들어,time.sleep(1)root.after(1000)TK에서.

그렇지 않으면time.sleep(), 많은 답변이 지적한 것, 그것이 가는 길이다.

지연은 타임 라이브러리, 특히 기능에서 이루어진다.

잠시 기다리게 하려면:

from time import sleep
sleep(1)

이는 다음과 같은 이유로 작동한다.

from time import sleep

시간 라이브러리에서만 절전 기능을 추출하면 다음과 같이 호출할 수 있다.

sleep(seconds)

타이핑을 해야 하는 것

time.sleep()

타이핑하기에 어색하게 긴.

이 방법으로는 시간 라이브러리의 다른 기능에 액세스할 수 없고, 라고 하는 변수를 가질 수 없다.sleep. 그러나 당신은 "라고 불리는 변수를 만들 수 있다.time.

모듈의 특정 부분만 원한다면 하는 것이 좋다.

다음과 같이 똑같이 할 수 있다.

import time
time.sleep(1)

입력만 하면 시간 라이브러리의 다른 기능에 액세스할 수 있음time.[function]()그러나 변수 시간은 가져오기를 덮어쓰기 때문에 생성할 수 없음.이에 대한 해결책

import time as t

시간 라이브러리를 다음과 같이 참조할 수 있다.t, 다음 작업을 수행할 수 있도록 허용:

t.sleep()

이것은 어느 도서관에서나 통한다.

Python 스크립트에 시간 지연을 적용하려면:

사용 또는 사용:

from threading import Event
from time import sleep

delay_in_sec = 2

# Use time.sleep like this
sleep(delay_in_sec)         # Returns None
print(f'slept for {delay_in_sec} seconds')

# Or use Event().wait like this
Event().wait(delay_in_sec)  # Returns False
print(f'waited for {delay_in_sec} seconds')

그러나 함수 실행을 지연시키려면 다음을 수행하십시오.

다음과 같이 사용하십시오.

from threading import Timer

delay_in_sec = 2

def hello(delay_in_sec):
    print(f'function called after {delay_in_sec} seconds')

t = Timer(delay_in_sec, hello, [delay_in_sec])  # Hello function will be called 2 seconds later with [delay_in_sec] as the *args parameter
t.start()  # Returns None
print("Started")

출력:

Started
function called after 2 seconds

왜 나중의 접근법을 사용하는가?

  • 전체 스크립트의 실행을 중지하지 않는다(전달하는 기능은 제외).
  • 타이머를 시작한 후에, 당신은 또한 다음과 같이 함으로써 타이머를 멈출 수 있다.timer_obj.cancel().

비동기식의잠을 자다

최신 파이톤 버전(Python 3.4 이상)에서 사용할 수 있는 알림asyncio.sleep비동기 프로그래밍과 비동기식 프로그래밍에 관련된 겁니다.다음 예제를 확인하십시오.

import asyncio
from datetime import datetime

@asyncio.coroutine
def countdown(iteration_name, countdown_sec):
    """
    Just count for some countdown_sec seconds and do nothing else
    """
    while countdown_sec > 0:
       print(f'{iteration_name} iterates: {countdown_sec} seconds')
       yield from asyncio.sleep(1)
       countdown_sec -= 1

loop = asyncio.get_event_loop()
tasks = [asyncio.ensure_future(countdown('First Count', 2)),
         asyncio.ensure_future(countdown('Second Count', 3))]

start_time = datetime.utcnow()

# Run both methods. How much time will both run...?
loop.run_until_complete(asyncio.wait(tasks))

loop.close()

print(f'total running time: {datetime.utcnow() - start_time}')

우리는 첫 번째 방법으로는 2초간, 그리고 두 번째 방법으로는 3초간, 즉 이 코드의 총 5초간 작동 시간이 "잠"이 올 것이라고 생각할 수 있다.그러나 다음과 같이 인쇄된다.

total_running_time: 0:00:03.01286

자세한 내용은 비동기 공식 문서를 읽는 것이 좋다.

다른 모든 사람들이 사실상의 제안을 했지만timeModule, I thought I'd sharing another method whatmatplotlibpyplot기능, .

from matplotlib import pyplot as plt
plt.pause(5)    # Pauses the program for 5 seconds

전형적으로 이것은 플롯이 짜여지는 즉시 사라지는 것을 막거나 조잡한 애니메이션을 만들기 위해 사용된다.

이것은 당신을 구해줄 것이다.import이미 가지고 있다면matplotlib수입된

이것은 시간 지연의 쉬운 예다.

import time

def delay(period='5'):
    # If the user enters nothing, it'll wait 5 seconds
    try:
        # If the user not enters a int, I'll just return ''
        time.sleep(period)
    except:
        return ''

또 다른, TKinter에서:

import tkinter

def tick():
    pass

root = Tk()
delay = 100 # Time in milliseconds
root.after(delay, tick)
root.mainloop()

다음 항목도 시도해 보십시오.

import time
# The time now
start = time.time() 
while time.time() - start < 10: # Run 1- seconds
    pass
# Do the job

이제 포탄은 충돌하거나 반응하지 않을 것이다.

참조URL: https://stackoverflow.com/questions/510348/how-can-i-make-a-time-delay-in-python

반응형