etc./StackOverFlow

파이썬에서 어떻게 시간 지연(time sleep)을 할 수 있습니까? [duplicate]

청렴결백한 만능 재주꾼 2021. 10. 27. 23:23
반응형

질문자 :user46646

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

Evan Fosmark

time 모듈 sleep() 함수를 사용할 수 있습니다. 1초 미만의 해상도를 위해 float 인수를 사용할 수 있습니다.

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

pobk

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

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

>>> from time import sleep >>> sleep(4)

이 함수는 실제로 운영 체제에서 호출한 스레드의 처리를 일시 중단하여 다른 스레드와 프로세스가 절전 모드에서 실행될 수 있도록 합니다.

그 목적으로 사용하거나 단순히 기능 실행을 지연시키는 데 사용합니다. 예를 들어:

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

"만세!"

Enter 키를

누른 후 3초 후에 가 인쇄됩니다.

다중 스레드 및 프로세스와 함께 sleep 를 사용하는 예

다시 말하지만 sleep 은 스레드를 일시 중단합니다. 즉, 거의 0에 가까운 처리 능력을 사용합니다.

시연하기 위해 다음과 같은 스크립트를 생성합니다(처음에는 대화형 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! >>>

빈 줄은 함수가 내 표준 출력에 인쇄되었음을 나타내며, 프롬프트에 있는지 확인하기 위해

Enter 키를 눌러야 했습니다.

이 방법의 장점은 Timer 스레드가 기다리는 동안 다른 작업을 수행할 수 있다는 것입니다. 이 경우

함수가 실행되기 전에 Enter 키를

한 번만 누르면 됩니다(첫 번째 빈 프롬프트 참조).

다중 처리 라이브러리 에는 해당 개체가 없습니다. 생성할 수 있지만 아마도 이유가 없을 것입니다. 하위 스레드는 완전히 새로운 하위 프로세스보다 간단한 타이머에 훨씬 더 적합합니다.

Aaron Hall

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

첫 번째 방법:

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

두 번째 지연 방법은 암시적 대기 방법을 사용하는 것입니다.

 driver.implicitly_wait(5)

세 번째 방법은 특정 작업이 완료될 때까지 또는 요소를 찾을 때까지 기다려야 할 때 더 유용합니다.

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

Humble_boy

졸린 생성기로 약간의 재미 .

시간 지연에 대한 질문입니다. 고정된 시간일 수 있지만 경우에 따라 지난 시간 이후 측정된 지연이 필요할 수 있습니다. 가능한 해결책은 다음과 같습니다.

마지막 시간 이후 측정된 지연(정기적으로 기상)

상황은 가능한 한 정기적으로 무언가를 하고 last_time 코드 주변의 모든 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)

보시다시피, 이 부저는 너무 단단하지 않으며 우리가 늦잠을 자고 규칙적인 일정에서 벗어나더라도 규칙적인 졸음 간격을 따라잡을 수 있습니다.

Jan Vlcinsky

: 오 개 내가 아는 방법이 있습니다 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')

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)

Trooper Z

Python 표준 라이브러리의 Tkinter 라이브러리는 가져올 수 있는 대화형 도구입니다. 기본적으로 코드로 조작하는 창으로 나타나는 버튼과 상자, 팝업 및 항목을 만들 수 있습니다.

Tkinter를 사용하는 경우 time.sleep() 사용하지 마십시오 . 프로그램이 엉망이 되기 때문입니다. 이것은 나에게 일어났다. 대신 root.after() 하고 몇 초 동안의 값을 밀리초로 바꾸십시오. 예를 들어 time.sleep(1) 은 Tkinter의 root.after(1000) 와 동일합니다.

그렇지 않으면 많은 답변이 지적한 time.sleep()

Parallax Sugar

지연은 시간 라이브러리 , 특히 time.sleep() 함수로 수행됩니다.

잠시만 기다리게 하려면:

from time import sleep sleep(1)

이것은 다음을 수행하기 때문에 작동합니다.

from time import sleep

시간 라이브러리 에서만 sleep 함수를 추출합니다. 즉, 다음을 사용하여 호출할 수 있습니다.

sleep(seconds)

타이핑을 하는 것보다

time.sleep()

입력하기에 어색하게 깁니다.

이 방법을 사용하면 시간 라이브러리 sleep 이라는 변수를 가질 수 없습니다. time 이라는 변수를 만들 수 있습니다.

from [library] import [function] (, [function2]) 은 모듈의 특정 부분만 원하는 경우에 좋습니다.

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

import time time.sleep(1)

time.[function]() 을 입력하는 한 time.clock() 과 같은 시간 라이브러리 의 다른 기능에 액세스할 수 있지만 가져오기를 덮어쓰므로 time 변수를 만들 수 없습니다. 이에 대한 해결책

import time as t

그러면 시간 라이브러리t 로 참조할 수 있으므로 다음을 수행할 수 있습니다.

t.sleep()

이것은 모든 라이브러리에서 작동합니다.

Matthew Miles

asyncio.sleep

최근 Python 버전(Python 3.4 이상)에서는 asyncio.sleep 을 사용할 수 있습니다. 비동기 프로그래밍 및 asyncio와 관련이 있습니다. 다음 예를 확인하세요.

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

자세한 내용은 asyncio 공식 문서 를 읽는 것이 좋습니다.

Aaron_ab

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

다음과 같이 time.sleep 또는 Event().wait 사용합니다.

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

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

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

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() 을 수행하여 타이머를 중지할 수도 있습니다.

BlackBeard

다른 모든 사람들이 사실상의 time matplotlibpyplot 기능인 pause 사용하여 다른 방법을 공유할 것이라고 생각했습니다.

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

일반적으로 플롯이 플롯되는 즉시 플롯이 사라지는 것을 방지하거나 조잡한 애니메이션을 만드는 데 사용됩니다.

이미 matplotlib 가져온 import 저장합니다.

Haran Rajkumar

다음은 시간 지연의 쉬운 예입니다.

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

LoneWolf

다음을 시도할 수도 있습니다.

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

이제 쉘이 충돌하거나 반응하지 않습니다.

Matthijs990

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

반응형