MacOS – Calling Python 3 script from AppleScript

applescriptautomatormacospythonterminal

I have a Python 3 script that I'd like to add as a Service using Automator. The idea is that I can right click on a text file, and an option will display to run my script on said file.

The shebang for my Python script is as follows:

#!/usr/bin/env python3

This script works fine and as expected in Terminal. However, when I attempt to automate this with AppleScript/Automator like so:

on run {input, parameters}

tell application "Terminal"
    do shell script "/path/to/script.py $@"
end tell

return input
end run

I run into issues, namely:

Terminal got an error: env: python3: No such file or directory

I've read here, among other places, that AppleScript by design only allows access to Unix commands, and will not for example source your bash profile (thus we do not have access to our $PATH by default). However I was under the impression that providing explicit paths was a workaround.

I've tried changing the do shell to this:

do shell script "/usr/bin/python3 /path/to/script.py $@"

and I've tried changing the shebang to this:

#!/usr/bin/env /usr/bin/python3

But nothing seems to work. Is it simply just not possible to execute a Python 3 script via AppleScript? I've not been able to find a viable workaround in my searches.

Edit: Additional info:

$ type -a python3
python3 is /usr/local/bin/python3

Best Answer

Solved my problem by changing the do shell to:

do shell script "/usr/local/bin/python3 /path/to/script.py $@"

and letting the shebang stay as:

#!/usr/bin/env python3