OS X: Using AppleScript with Canopy Python

When using Mac OS X's AppleScript shell functionality, users may notice that the command

do shell script "python <path-to-py-file>"

will fail, usually because of an ImportError for a package they know to be installed in their Canopy User environment. The failure is due to AppleScript not using Canopy's Python, but instead the system Python located at `/usr/bin/python`. You can verify this for any command by running a script such as the following:

do shell script "which python" 

The "do shell script" command doesn't provide the same environment as the Terminal. Most importantly, the PATH environment variable (pointing to Canopy User Python) is completely stripped down. For curious readers, Apple explains why in their documentation:

My command works fine in Terminal, but when I try to use it in do shell script, I get an error about "command not found." What’s going on?

There are two possibilities. First, do shell script always uses /bin/sh to interpret your command, not your default shell, which Terminal uses. (To find out what your default shell is, say echo $SHELL in Terminal.) While some commands are the same between shells, others are not, and you may have used one of them. If you write your do shell script scripts in Terminal first, always use sh. You can start sh by typing /bin/sh; type exit to get back to your normal shell.

Second, when you use just a command name instead of a complete path, the shell uses a list of directories (known as your PATH) to try and find the complete path to the command. For security and portability reasons, do shell script ignores the configuration files that an interactive shell would read, so you don’t get the customizations you would have in Terminal. Use the full path to the command, for example, /sbin/ifconfig instead of just ifconfig. To find the full path in Terminal, say which command-name, for example, which ifconfig; to see the list of places do shell script will search, say do shell script \"echo $PATH\".

The solution should only require a few more details in your AppleScript. For example, try the following (replacing "64bit" with "32bit" on such systems):

do shell script "/Users/<your-username>/Library/Enthought/Canopy_64bit/User/bin/python <path-to-py-file>"
Have more questions? Submit a request

Comments

  • Avatar
    David Barber

    This was precisely what I needed to make several of my python programs run using an AppleScript that runs at selected times.  Thanks!

Powered by Zendesk