파이썬에서 시간 지연을 어떻게 만들 수 있습니까?[복제하다]


질문

 

파이썬 스크립트에서 시간 지연을 넣는 방법을 알고 싶습니다.


답변

 

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).


답변

시간 모듈에서 Sleep () 함수를 사용할 수 있습니다.Sub-Second 해상도의 float 인수를 사용할 수 있습니다.

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


답변

파이썬에서 시간 지연을 어떻게 만들 수 있습니까?

단일 스레드에서는 수면 기능을 제안합니다.

>>> from time import sleep

>>> sleep(4)

이 함수는 실제로 운영 체제에서 호출되는 스레드 처리를 일시 중단하여 다른 스레드 및 프로세스가 잠자는 동안 실행되도록합니다.

그 목적으로 사용하거나 간단히 사용하는 기능을 지연시키는 것입니다.예를 들어:

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

"천시!"Enter 키를 누른 후 3 초 동안 인쇄됩니다.

예제 여러 스레드 및 프로세스가있는 수면을 사용합니다

다시, 수면은 스레드를 일시 중단합니다. 그것은 ZERO PROCESSION POWER 옆에 사용합니다.

이와 같은 스크립트를 작성하려면 (방문 파이썬 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

멀티 스레딩

나중에 타이머 스레딩 객체가있는 별도의 스레드에서 나중에 호출되는 함수를 트리거 할 수 있습니다.

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

>>>

빈 줄은 내 표준 출력으로 인쇄 된 함수가 인쇄되어야하며 프롬프트가되었는지 확인해야합니다.

이 방법의 위쪽은 타이머 스레드가 기다리고있는 동안 다른 일을 할 수있었습니다.이 경우 함수가 실행되기 전에 한 번 입력하십시오 (첫 번째 빈 프롬프트 참조).

다중 프로세싱 라이브러리에는 각각의 객체가 없습니다.하나를 만들 수는 있지만 이유는 아마도 존재하지 않습니다.하위 스레드는 완전히 새로운 하위 프로세스보다 간단한 타이머에 대해 훨씬 더 의미가 있습니다.



답변

지연은 다음 방법을 사용하여 구현할 수 있습니다.

첫 번째 방법 :

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.time.wait (), matplotlib의 pyplot.pause (), .after () 및 asyncio.sleep ()를 알고있는 5 가지 방법이 있습니다.


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

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

pygame.time.wait () 예제 (PyGame 창을 사용하지 않으면 권장되지 않지만 즉시 창을 종료 할 수 있으므로) :

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')

matplotlib의 함수 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 Time STUME을 우리의 코드 주위에 괴롭히지 않으려 고합니다.

부저 발전기

다음 코드 (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

정규 Buzzergen을 호출합니다

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)

우리가 보는 것처럼,이 부저는 너무 단단하지 않고 우리가 오버링하고 정규 일정에서 벗어나더라도 정기적 인 졸린 간격으로 따라 잡을 수있게 해줍니다.

출처:https://stackoverflow.com/questions/510348/how-can-i-make-a-time-delay-in-python