|Ned Batchelder : Blog | Code | Text | Site|
Versioned Python commands on Mac
» Home : Blog : December 2013
I was experimenting with pydoc yesterday, and was baffled by how it was running. Turns out Mac OS X does some tricky stuff to support multiple versions of Python.
If you type "pydoc" at a shell prompt, it works properly:
If you ask which file is being run, it's /usr/bin/pydoc, and you can look at that file:
Notice that this file will always write "python version X.Y.Z can't run...," which is not the output we're getting. Weird!
(BTW, if you have activated a virtualenv, you may have an alias, so that "pydoc" is actually "python -m pydoc". Is there an equivalent to "which" that will include that fact it in its output?)
But even without the virtualenv alias, this file isn't being run. Why not? The answer is in the shebang line:
Unix uses the shebang line to find a program to run the file. So typing "pydoc" at the prompt will find /usr/bin/pydoc, then find the shebang line, and will actually run this:
Seems simple enough: invoke Python, and have it run the code in /usr/bin/pydoc. So why isn't Python running the Python code we saw? The answer is that /usr/bin/python is not a Python interpreter!
On OS X, /usr/bin/python examines various settings and then invokes a real Python interpreter of the correct version: python.1 man page. A quick look at the readable text inside the executable confirms that it is not a full interpreter, and that it is concerned with versions:
So this finder is given "/usr/bin/pydoc" as an argument, and it decides what to really run. It's special-casing "/usr/bin", and actually invoking /usr/bin/pydoc2.7. The real /usr/bin/pydoc file is there only to be executed when the version-selection mechanism fails, which is why it simply prints messages about not being able to find the right version.
It seems that the switcher doesn't care much what command you're trying to run. If it's in /usr/bin, and there's a file alongside it with the same name but the current Python version appended, then it will run the versioned one.
All this can be verified by an experiment. I created /usr/bin/foo with these contents:
and a /usr/bin/foo2.7 with this:
Then I ran it a number of different ways (the current directory is in the prompt):
Notice that the Python switcher runs the versioned file whenever it's identified as being from /usr/bin. But when run so that the shell doesn't identify it that way, even when it's the exact same file, the Python switcher decides it shouldn't interfere, and it runs the exact file specified.