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

Randall Leeds randall.leeds at gmail.com
Wed Jan 11 00:53:40 CET 2012

On Tue, Jan 10, 2012 at 15:51, Maciej Fijalkowski <fijall at gmail.com> wrote:
> On Wed, Jan 11, 2012 at 1:44 AM, kgardenia42 <kgardenia42 at googlemail.com> wrote:
>> Hi,
>> 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:
>>   ./main.py
>> and it will use pypy if installed, otherwise fallback to normal python.
>> In the archives of this list I found the following idiom:
>> try:
>>    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.
>> Thanks.
>> _______________________________________________
>> pypy-dev mailing list
>> pypy-dev at python.org
>> http://mail.python.org/mailman/listinfo/pypy-dev
> You can either do that, or do something like:
> if_pypy_installed (however you check it depends on your os/distro):
>  os.system(pypy, sys.argv) with correct parsing of argv and putting
> it there, not sure how to do it ;-)

I would use the os.exec* family of functions to just replace the
current process with pypy invoked with the same arguments.

More information about the pypy-dev mailing list