Use Automator to run Python script when files added to folder

automatorpythonterminal

I have a folder, Books, where I add all of the .pdf files that need to be uploaded to a Kindle. I have a Python script that does that, but instead of manually running it, I want to check whenever files are added to Books, run that Python script. Is there any way to do this using Automator, or even without Automator?

Best Answer

Launch Automator, and choose 'Folder Action' as the document type. Then set the target folder in the drop-down menu at the top of the window.

Add a "Run Shell Script" action. You have to choose one of the 'shell' environments in the drop-down menu, which include either the system python /usr/bin/python (which is v2, and EOLed); or a Unix shell, where you can call the python script externally, with something like:

/usr/local/bin/python3 <path to python script> "$1"

Alternatively to using the Run Shell Script action, you could use the AppleScript action with a do shell script command.

Save your workflow. The workflow is saved to ~/Library/Scripts/Folder Action Scripts

You can configure Folder Actions for any folder by right-clicking in the Finder and selecting "Folder Actions Setup".

(I have had intermittent success hacking the saved workflow in a text editor, and altering the 'shell' path to another environment. /usr/bin/swift works, but /usr/local/bin/python doesn't. More work required.)