The basic usage is quite simple. We just need two files.
watch.py
#! /usr/bin/python from time import gmtime, strftime fn = '/Users/telliott_admin/Desktop/time.txt' FH = open(fn,'w') FH.write(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())) FH.close() |
Make sure the script is executable (I did chmod 755), and copy it to ~/Library/Scripts.
The other file is a plist that shows the details for what we want launchd to do:
com.TE.script.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.TE.script</string> <key>LowPriorityIO</key> <true/> <key>Program</key> <string>/Users/telliott_admin/Library/Scripts/script.py</string> <key>RunAtLoad</key> <true/> <key>ProgramArguments</key> <array> <string>script.py</string> </array> <key>WatchPaths</key> <array> <string>/Volumes/HD/Users/telliott_admin/Desktop/y.txt</string> </array> </dict> </plist> |
The plist goes in ~/Library/LaunchAgents.
There are many additional things you could do---the man page is here.
The script just writes the current time to a file on my Desktop. It is set to RunAtLoad (normally that would be login, but see below), and whenever the WatchPath changes. Here that is just a file which is also on my Desktop, but it could be a directory.
We can see if it's been loaded by doing:
> launchctl list | grep "com.TE"
>
Not yet.
We can manually (un)load it by doing:
launchctl load ~/Library/LaunchAgents/com.TE.script.plist
> launchctl list | grep "com.TE"
- 0 com.TE.script
When we do that we should see the file time.txt appear on the Desktop because we set RunAtLoad to true. Also, if the file y.txt is altered, say by:
> touch ~/Desktop/y.txt
The script should execute again.