How do I use caffeinate to prevent my computer from sleeping while a script runs?

-s option is commonly used with laptops (If the lid is closed, the system does to forced sleep). -s only applies when not using a battery - if there is limited power in the battery the system will sleep no matter what.

-i is for idle sleep which happens when the system has not been used for a certain period.

Note you can use both options keep the system perky if required:

caffeinate -is python spam.py

From the Mac developer library, the differences between idle sleep and (forced) sleep are:

  • Forced sleep occurs when the user takes some sort of direct action to cause the machine to sleep. Closing the lid on a laptop or selecting sleep from the Apple menu both cause forced sleep. The system will also induce forced sleep under certain conditions, for example, a thermal emergency or a low battery.

  • Idle sleep occurs when the machine is unused for a specific period of time configured in the Energy Saver System Preferences