让Python程序等待

ric*_*lla 10 python

我需要让我的python程序等待200ms才能轮询一些描述的输入.例如,在C#中,我可以Thread.Sleep()用来实现这一点.在python中执行此操作的最简单方法是什么?

Tha*_*vas 23

使用时间模块.

例如,延迟1秒:

import time
time.sleep(1) # delay for 1 seconds
Run Code Online (Sandbox Code Playgroud)

在您的情况下,如果您想获得200毫秒,请使用此代码:

time.sleep(0.2)
Run Code Online (Sandbox Code Playgroud)

time.sleep也适用于float.


cni*_*tar 8

如果您只想睡觉,可以尝试:

import time

time.sleep(0.2)
Run Code Online (Sandbox Code Playgroud)


小智 7

您可以sleep()在模块中使用该方法time.

首先,您必须time在程序中导入模块.之后,您可以调用该sleep()函数.

将其添加到您的代码中:

import time
time.sleep(0.2)
Run Code Online (Sandbox Code Playgroud)


Mat*_*les 5

使用时间库并使用命令time.sleep()使其等待。选择从时间库中提取出来然后仅使用sleep()时,效率更高。例如:

import time
print('hi')
time.sleep(0.2)
print('hello')
Run Code Online (Sandbox Code Playgroud)

改进的:

from time import sleep
print('Loading...')
sleep(2)
print('Done!')
Run Code Online (Sandbox Code Playgroud)

注意:以秒为单位而不是毫秒。