starting repl programmatically

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu May 20 20:51:34 EDT 2010


On Thu, 20 May 2010 17:11:17 -0700, Brendan Miller wrote:

> python -i myscript.py
> 
> almost does what I want. The only problem is if I exit with exit(0) it
> does *not* enter interactive mode. I have to run off the end of the
> script as near as I can tell. Is there another way to exit without
> breaking python -i?

Upgrade to Python 2.6 and it will work as expected.

[steve at sylar ~]$ python2.6 -i -c "import sys; sys.exit(0)"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
SystemExit: 0
>>>



If you're stuck with 2.5, you can wrap your script in a try...except and 
catch the exit:


[steve at sylar ~]$ python -i -c "import sys
> try:
>     x = 2
>     sys.exit(0)
> except SystemExit:
>     pass
> "
>>> x
2


The only side-effect I can think of is that you may lose any non-zero 
result codes, but you probably do that after entering interactive mode 
anyway.

If you want to be fancy, you can inspect the state of the environment 
variable and Python options inside the except block, and re-raise if 
necessary. Untested:

except SystemExit:
    if os.getenv('PYTHONINSPECT'):
        pass
    else:
        raise


I can't find a way to check for a -i switch from inside Python 2.5. There 
is a sys.flags but it is only available in Python 2.6 or higher.



-- 
Steven



More information about the Python-list mailing list