9

Is there a way to prevent a computer running OS X from going to sleep from within a Python script?

christianbrodbeck
  • 1,845
  • 2
  • 18
  • 23
  • Not a programming answer, but [Caffeine](https://itunes.apple.com/us/app/caffeine/id411246225) is a nice freeware app which stops your computer falling asleep when activated. – Alex Jan 08 '13 at 13:27
  • Thanks @Alex, I've come across several apps that do this, but doing it from inside the script would be cleaner... – christianbrodbeck Jan 08 '13 at 13:30

5 Answers5

11

You can use the built-in caffeinate command.

subprocess.Popen('caffeinate')

This is how I use it:

import sys
import subprocess

if 'darwin' in sys.platform:
    print('Running \'caffeinate\' on MacOSX to prevent the system from sleeping')
    subprocess.Popen('caffeinate')
idbrii
  • 10,113
  • 5
  • 57
  • 100
guya
  • 4,733
  • 34
  • 28
3

Since OS 10.6, you have to make use of the IOPMAssertion family of functions, available in Cocoa. This is really well explained there.

Then, you will have to call it from Python. I'm not sure that there're already specific bindings for Cocoa in Python, but you can call Objective-C functions. It is really well described here.

Community
  • 1
  • 1
dasilvj
  • 10,278
  • 2
  • 15
  • 16
  • So, that would involve using ctypes to implement listing 2 of [qa1340](http://developer.apple.com/library/mac/#qa/qa1340/_index.html)? Are there instructions for that? (E.g., how can I retrieve a value such as kIOPMAssertionTypeNoDisplaySleep?) – christianbrodbeck Jan 08 '13 at 18:02
3

You can also run caffeinate in an external terminal window and leave it open to achieve what the OP wants.

  1. open a terminal

  2. type caffeinate

  3. press Enter

Once you have done this, your Mac will stay awake for as long as you leave the Terminal running.

You can minimize or hide it, and your Mac will not go to sleep until you use the keyboard shortcut Ctrl+C to interrupt the command.

source

JacoSolari
  • 1,044
  • 10
  • 23
0

There is a Python utility that illustrates how to raise the required assertions in Python directly: https://github.com/minrk/appnope

christianbrodbeck
  • 1,845
  • 2
  • 18
  • 23
  • appnope is about preventing App Nap not system sleep. See: https://github.com/minrk/appnope/blob/daac76517da8aba6fd0614eb1ab37d9b8ee39633/appnope/_nope.py#L78 – UloPe Nov 06 '19 at 16:17
  • Just look a little further up in the code for the other constants – christianbrodbeck Nov 08 '19 at 00:53
  • Yes, the constants are there but the functionality is not exposed via the documented `nope()` API. – UloPe Nov 08 '19 at 08:48
0

For that, here's a simple script: https://github.com/octavian-negru/keep-pc-awake/blob/master/awake.py

E.g. pyhton -m awake 19 (stay awake until 19:00). To stay awake forever, just pass 25 as the argument.

asdf
  • 31
  • 5