Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a python script continue running while mac is locked

Tags:

python

macos

I'm currently working on a python script that takes some hours to finish. I'm working in a shared office and I want (if possible) lo lock my mac m1 in order to make sure nobody can access it and at the same time keep the script running.

like image 220
luca sala Avatar asked Jul 21 '26 23:07

luca sala


2 Answers

It can be done manually like so, assuming the system is plugged in throughout:

MacOS 13

  1. Settings > Displays > Advanced... (bottom-right) > Prevent automatic sleeping on power adapter when the display is off - Turn on
  2. Settings > Privacy & Security > Advanced... (bottom-right) > Log out automatically after inactivity - Turn off

MacOS 12

  1. Settings > Battery > Power Adapter > Prevent your Mac from automatically sleeping when display is off
  2. Settings > Security & Privacy > Advanced... (bottom-right) > make sure "Log out after [x] minutes" is disabled

Once you lock your screen now (Apple icon top-left or the power button), your computer should stay awake. Note that if you close the lid, the system will sleep

like image 121
Ariel Lubonja Avatar answered Jul 24 '26 11:07

Ariel Lubonja


There's a library just for this purpose*: wakepy.

Since you do not require the screen to be on, you could use the keep.running mode, like this:

from wakepy import keep

with keep.running(on_fail='warn'):
    # Call the function that takes a long time. 
    # You may lock the session and turn the screen off but CPU will keep running

With this you do not have to fiddle with your power settings, and since it's cross-platform you can share your script with your colleagues using Windows or Linux, too.


*full disclosure: I'm the author of the package

like image 26
np8 Avatar answered Jul 24 '26 13:07

np8