在Python中使用usleep

Fed*_*can 28 python

我在Python 2.7中搜索usleep()函数.

有人知道它是否确实存在,可能还有其他功能名称吗?

Mik*_*wis 42

由于usleep通常意味着您希望延迟执行x微秒,因此必须将秒值除以1000000.

import time
time.sleep(seconds/1000000.0)
Run Code Online (Sandbox Code Playgroud)

time.sleep() 以秒为参数.

http://docs.python.org/library/time.html#time.sleep

  • 小心,阅读[睡眠准确度()](http://stackoverflow.com/questions/1133857/how-accurate-is-pythons-time-sleep) (11认同)

Fáb*_*niz 25

import time
usleep = lambda x: time.sleep(x/1000000.0)

usleep(100) #sleep during 100?s
Run Code Online (Sandbox Code Playgroud)


小智 7

对 time.sleep 非常小心。我使用 time.sleep 被 python3 烧毁,因为它是非单调的。如果挂钟向后更改,则 time.sleep 调用将不会完成,直到挂钟赶上睡眠按计划进行时的位置。我还没有找到 python 的单调阻塞睡眠。

相反,我推荐 Event.wait,如下所示:

def call_repeatedly(interval, func, *args, **kwargs):
    stopped = Event()
    def loop():
        while not stopped.wait(interval):  # the first call is in `interval` secs
            try:
                func(*args)
            except Exception as e:
                logger.error(e);
                if kwargs.get('exception'):
                    kwargs.get('exception')(e) # SEND exception to the specified function if there is one.
                else:
                    raise Exception(e)
    Thread(target=loop).start()
    return stopped.set
Run Code Online (Sandbox Code Playgroud)

http://pastebin.com/0rZdY8gB

  • 我相信`time.sleep` 现在在 Python 3 中应该是单调的;至少,[源代码](https://github.com/python/cpython/blob/v3.6.3/Modules/timemodule.c#L1430) 说`_PyTime_GetMonotonicClock()` 来获取当前时间。我不能肯定地说过去的行为是什么样的。 (6认同)

小智 7

三行调用“原始”usleep:

import ctypes

libc = ctypes.CDLL('libc.so.6')
libc.usleep(300000)
Run Code Online (Sandbox Code Playgroud)

在centos和alpine上测试python 3.8.1


luc*_*luc 6

from time import sleep
sleep(0.1) #sleep during 100ms
Run Code Online (Sandbox Code Playgroud)