防止睡眠模式python(python上的Wakelock)

新手上路,请多包涵

我如何在不使用不同操作系统(Ubuntu,Windows …)上的额外应用程序的情况下防止 python 上的睡眠模式,但在大多数情况下我需要 Linux 解决方案

我正在制作可以大量使用的应用程序。它使用了大约 80% 的 CPU,所以用户只需启动这个应用程序并离开键盘。所以我想我需要像系统 api 或锁定睡眠模式的库之类的东西。我敢肯定,它存在。例如,如果您在操作系统上打开任何视频播放器,您的(PC、笔记本电脑)将不会进入睡眠模式,浏览器也是如此。

此外,在 Android ( WakeLock ) 或 Windows (SetThreadExecutionState) 中也有同样的事情

原文由 Max Dev 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 986
1 个回答

我遇到了类似的情况,一个进程花费了足够长的时间来执行它自己,以至于 Windows 会休眠。为了克服这个问题,我写了一个脚本。

下面一段简单的代码可以防止这个问题。使用时,它会要求 Windows 在脚本运行时不要休眠。 (在某些情况下,例如当电池电量耗尽时,Windows 将忽略您的请求。)

     class WindowsInhibitor:
        '''Prevent OS sleep/hibernate in windows; code from:
        https://github.com/h3llrais3r/Deluge-PreventSuspendPlus/blob/master/preventsuspendplus/core.py
        API documentation:
        https://msdn.microsoft.com/en-us/library/windows/desktop/aa373208(v=vs.85).aspx'''
        ES_CONTINUOUS = 0x80000000
        ES_SYSTEM_REQUIRED = 0x00000001

        def __init__(self):
            pass

        def inhibit(self):
            import ctypes
            print("Preventing Windows from going to sleep")
            ctypes.windll.kernel32.SetThreadExecutionState(
                WindowsInhibitor.ES_CONTINUOUS | \
                WindowsInhibitor.ES_SYSTEM_REQUIRED)

        def uninhibit(self):
            import ctypes
            print("Allowing Windows to go to sleep")
            ctypes.windll.kernel32.SetThreadExecutionState(
                WindowsInhibitor.ES_CONTINUOUS)

要运行脚本,只需:

     import os

    osSleep = None
    # in Windows, prevent the OS from sleeping while we run
    if os.name == 'nt':
        osSleep = WindowsInhibitor()
        osSleep.inhibit()

    # do slow stuff

    if osSleep:
        osSleep.uninhibit()

原文由 mishsx 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题