Run Python Script on computer boot

bootpython

How can I create a python script that runs when the computer boots? I know to get it to run on login I can turn it into an app and add it to a as a startup item in settings, but I need it to run once the computer boots.

How can I make a python script run when the computer is turned on?

I am running MacOS High Sierra 10.13.1 and Python 2.7.10

Best Answer

Use a plist like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>com.username.scriptname</string>    
  <key>ProgramArguments</key>
  <array>
    <string>/usr/bin/python</string>
    <string>/path/to/script.py</string>
  </array>    
  <key>RunAtLoad</key>
  <true/>    
  <key>StandardErrorPath</key>
  <string>/tmp/com.username.scriptname.err</string>    
  <key>StandardOutPath</key>
  <string>/tmp/com.username.scriptname.out</string>
</dict>
</plist>

Just make sure you replace the /path/to/script.py accordingly and then save it to your desktop. Then open up terminal and type sudo chown root:wheel /path/to/plistfile it will prompt for password type it in in and when you are typing it it won't give you any visual feedback then press enter. Then type sudo chmod 644 /path/to/.plistfile. Then just sudo mv ... the plist file in /Library/LaunchDaemons/ or /Library/LaunchAgents/ and finally sudo launchctl load ... the plist and your script will run.

And if you have any problem comment below and also tell me the OS your Mac is running.