Search code examples
pythonmacosbootlaunchd

running a python script on Mac boot


I'm trying to get a python script to run on startup. I have the following file: com.test.service.plist :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC -//Apple Computer//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd >
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.test.service</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/sh</string>
        <string>/var/www/html/app/appstart.sh</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>

copied to ~/Library/LaunchAgents/

loaded as

launchctl load -w ~/Library/LaunchAgents/com.test.service.plist

the script has 2 lines:

/usr/bin/python /var/www/html/app/app.py
echo "hello" >> /var/www/html/app/test.txt

the script runs (the file test.txt gets created with 'hello' in it) however, the app.py doesn't run. for testing purposes, all i did inside the app.py was:

import os
os.system("echo 'python' >> /var/www/html/app/test.txt")

if i just run the appstart.sh in terminal, then python runs no problem

i followed instructions in this question already, but no luck


Solution

  • Some time ago I used cron to do just that. You can make an entry like this

    @reboot /path/to/my/script

    more info about cron

    The path to my script will be the path to your appstart.sh file.

    So you open your terminal.

    You type in crontab -e (this will open a file in your default editor, problably nano)

    You scroll down and on the bottom of the file you type @reboot /path/to/file

    Then you save and exit.