[pypy-dev] Use pypy if available otherwise fallback to CPython

kgardenia42 kgardenia42 at googlemail.com
Wed Jan 11 00:44:10 CET 2012


I have some python code (lets call it main.py) which I'd like to run
with pypy if available/installed but otherwise fallback to CPython.

Clearly if I call my main.py explicitly with either "pypy" or "python"
as follows then I will get the behavior I want:

   python main.py
   pypy main.py

However, my goal is that main.py is executable and I can just do:


and it will use pypy if installed, otherwise fallback to normal python.

In the archives of this list I found the following idiom:

    import __pypy__
except ImportError:
    __pypy__ = None

However, I don't think this helps me here.  It seems like (and correct
me if I'm wrong) the code just detects python vs pypy when it has
already been run with one or the other.  It doesn't accomplish my
stated goal and it seems like that idiom would only make sense if I
wanted custom code to run depending on whether I run from python or
pypy.  Did I miss something?

So otherwise, what can I put in the shebang line of my main.py to
accomplish my goal?  I assume if I make it /usr/bin/python then I will
just always use CPython (irregardless of whether I do the import
__pypy__ trick).  So all I can think of is the rather brute-force
approach of creating my own wrapper shell script (e.g.
/usr/bin/python-selector) which delegates to pypy if available but
otherwise uses /usr/bin/python.  I then put #!/usr/bin/python-selector
as the shebang line of my main.py.  Does that make sense?

I'm pretty sure I must be missing a trick here and there is a better way.

Any guidance welcome.


More information about the pypy-dev mailing list