问题
Is there a way to prevent a computer running OS X from going to sleep from within a Python script?
回答1:
You can call the 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')
回答2:
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.
回答3:
By now there is a Python utility to raise the required assertions, comes with Anaconda: https://github.com/minrk/appnope
来源:https://stackoverflow.com/questions/14215960/prevent-os-x-from-going-to-sleep-with-python