Python: как ждать определенного времени
В языке программирования Python для задержки выполнения программы на определенное количество времени используется модуль time и его функция sleep .
Функция sleep
Функция sleep приостанавливает выполнение программы на заданное количество секунд. Время задается в секундах и может быть дробным.
Пример использования
В этом примере после вывода сообщения «Сначала» программа останавливается на 5 секунд, после чего выводится сообщение «Потом».
Ограничения функции sleep
Функция sleep приостанавливает выполнение всего потока, в котором она вызывается. Это означает, что ничего другого в этом потоке не будет выполняться во время задержки.
Альтернативы sleep
Если вы хотите приостановить выполнение определенного кода, не останавливая весь поток, можно использовать библиотеки для асинхронного программирования, такие как asyncio.
Функция sleep из модуля time — это удобный и простой способ приостановить выполнение программы на Python на определенное количество времени. Однако она приостанавливает весь поток, поэтому для более сложных задач можно использовать асинхронное программирование.
Python sleep()
The sleep() function suspends (waits) execution of the current thread for a given number of seconds.
Python has a module named time which provides several useful functions to handle time-related tasks. One of the popular functions among them is sleep() .
The sleep() function suspends execution of the current thread for a given number of seconds.
Example 1: Python sleep()
Here’s how this program works:
- «Printed immediately» is printed
- Suspends (Delays) execution for 2.4 seconds.
- «Printed after 2.4 seconds» is printed.
As you can see from the above example, sleep() takes a floating-point number as an argument.
Before Python 3.5, the actual suspension time may be less than the argument specified to the time() function.
Since Python 3.5, the suspension time will be at least the seconds specified.
Example 2: Python create a digital clock
In the above program, we computed and printed the current local time inside the infinite while loop. Then, the program waits for 1 second. Again, the current local time is computed and printed. This process goes on.
When you run the program, the output will be something like:
Here is a slightly modified better version of the above program.
Multithreading in Python
Before talking about sleep() in multithreaded programs, let’s talk about processes and threads.
A computer program is a collection of instructions. A process is the execution of those instructions.
A thread is a subset of the process. A process can have one or more threads.
Example 3: Python multithreading
All the programs above in this article are single-threaded programs. Here’s an example of a multithreaded Python program.
When you run the program, the output will be something like:
The above program has two threads t1 and t2 . These threads are run using t1.start() and t2.start() statements.
Note that, t1 and t2 run concurrently and you might get different output.
Visit this page to learn more about Multithreading in Python.
time.sleep() in multithreaded programs
The sleep() function suspends execution of the current thread for a given number of seconds.
In case of single-threaded programs, sleep() suspends execution of the thread and process. However, the function suspends a thread rather than the whole process in multithreaded programs.
Метод time.sleep() в Python
Метод python sleep(), используемый для приостановки выполнения для заданного времени (в секундах). Мы можем использовать функцию ожидания python, чтобы остановить выполнение программы за заданное время в секундах. Фактическое время приостановки может быть меньше запрошенного, потому что любой пойманный сигнал прекратит сон() после выполнения ловушки этого сигнала. Кроме того, время приостановки может быть больше, чем запрашивается произвольной суммой из-за планирования другой активности в системе. Вы можете установить задержку в своем скрипте Python, передав количество секунд, которые вы хотите отложить, к функции сна.
Когда вы запустите приведенный выше Пример:, он завершится только через пять секунд.
Метод sleep() поддерживает числа с плавающей запятой, что означает, что вы можете заставить его также ждать доли секунды.
Когда вы запускаете приведенный выше Пример:, программа ждет завершения 1 секунды и 500 миллисекунд.
Задержка времени для бесконечного цикла
Вот еще один пример когда что-то выполняется примерно каждые 5 секунд.
Вышеупомянутая программа запускает бесконечный цикл, поэтому вы должны принудительно остановить программу, когда захотите.
Сон программы
Следующая программа представляет собой пример обратного отсчета, используя метод ожидания, чтобы подождать 1 секунду каждого номера.
Thread и Sleep
Темы, как правило, содержатся в процессах. В рамках одного процесса может существовать более одного потока. Эти потоки разделяют память и состояние процесса. В следующем примере вы можете увидеть, как метод sleep() работает в многопроцессорной программе.
Correct way to pause a Python program
I’ve been using the input function as a way to pause my scripts:
Is there a formal way to do this?
![]()
17 Answers 17
It seems fine to me (or raw_input() in Python 2.X). Alternatively, you could use time.sleep() if you want to pause for a certain number of seconds.
![]()
For Windows only, use:
![]()
So, I found this to work very well in my coding endeavors. I simply created a function at the very beginning of my program,
and now I can use the pause() function whenever I need to just as if I was writing a batch file. For example, in a program such as this:
Now obviously this program has no objective and is just for example purposes, but you can understand precisely what I mean.
NOTE: For Python 3, you will need to use input as opposed to raw_input
I assume you want to pause without input.
![]()
I have had a similar question and I was using signal:
So you register a handler for the signal SIGINT and pause waiting for any signal. Now from outside your program (e.g. in bash), you can run kill -2 <python_pid> , which will send signal 2 (i.e. SIGINT) to your python program. Your program will call your registered handler and proceed running.
I use the following for Python 2 and Python 3 to pause code execution until user presses Enter
![]()
As pointed out by mhawke and steveha’s comments, the best answer to this exact question would be:
For a long block of text, it is best to use input(‘Press <ENTER> to continue’) (or raw_input(‘Press <ENTER> to continue’) on Python 2.x) to prompt the user, rather than a time delay. Fast readers won’t want to wait for a delay, slow readers might want more time on the delay, someone might be interrupted while reading it and want a lot more time, etc. Also, if someone uses the program a lot, he/she may become used to how it works and not need to even read the long text. It’s just friendlier to let the user control how long the block of text is displayed for reading.
Anecdote: There was a time where programs used "press [ANY] key to continue". This failed because people were complaining they could not find the key ANY on their keyboard 🙂