Prevent OS X from going to sleep with Python?

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')

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