kitchen800
kitchen800

Reputation: 227

Run python script each time mac wakes from sleep

I have a python file that I want to run every time the mac comes out of its sleep. I have turned the .py file into an dmg file and placed into login items section of the mac this is in settings -> users -> login items. My problem is that this seems to only run the DMG file when i fully logout of the the mac. I always just click the sleep option on the mac. Is there a way to run the python script each time the computer wakes up from a sleep? enter image description here

Upvotes: 1

Views: 1218

Answers (1)

J minding
J minding

Reputation: 53

@kitchen800 you can try making a shell script that runs your python program, or like another suggestion, use pyinstaller/py2app to make it into a executable application. Putting the python program itself in the Open at login will simply open the python script, not run it.

Method 1: Make it a shell script

  1. Make a file called runpyscript.sh (the file name doesn't matter, but keep the .sh)
  2. Open the file with a text editor/IDE and write in it
python3 path/to/file.py
  1. Save the file and navigate to your terminal
  2. Run the command chmod +x path/to/runpyscript.sh
  3. You can also get rid of the .sh at the end of the file to make it executable by double-clicking
  4. Add this shell script to "Open at login".
    Now, when you login, it should (hopefully work and) open this shell script in terminal and run your python program.

Method 2: Make it an application with pyinstaller

  1. Navigate to terminal
  2. Put this in: pip install pyinstaller (if you haven't installed pyinstaller already)
  3. Now put this in: pyinstaller path/to/file --onefile <other options go here>
    For more on the options, you can go to this link: https://pyinstaller.readthedocs.io/en/stable/usage.html
  4. Now, you should have a .app file. Navigate to your finder, press CMD+SHIFT+H, and go to the folder called dist. There, you should find a file_name_here.app and you can put it in Open at login.

Method 3: Make it an application with py2app

  1. Navigate to terminal
  2. In the command prompt, put pip install py2app
  3. Next, write cd path/to/file.
  4. Now, you can generate a setup.py file for your python application. In the command prompt, write py2applet --make-setup file_name_here.py
  5. Once you have that done, you can do python3 setup.py py2app -A to construct the app in alias mode. In the same directory, go to the folder called dist in Finder and open it. You should find a .app file in it. If anything goes wrong while opening the .app file, then configure setup.py and run rm -rf build dist and the above setup.py command again until it works.
  6. Then, go back to terminal and write python3 setup.py py2app to build the final version of the app.
  7. Once you're done, put it in Open at login.

Upvotes: 2

Related Questions