IPython scripting - Exit script with status code
Question: I am trying to use ipython to script git pre-commit hooks since it has a nice
syntax to run shell commands and converting the stdout result into a list of
strings (which makes for easy processing).

I need to return a status code != 0 from the ipython script so that git pre-
commit hook will abort the commit.

Consider this example script

    
    
    #! /bin/ipython
    import sys
    sys.exit(1)
    

running it from the shell

    
    
    $ ipython test.ipy
    

but then checking the status code with `$ echo $?` always returns `0`

Is there a way to make ipython return a non-zero status code?


Answer: Open up ipython and try running that code interactively.

    
    
    In [1]: import sys
    In [2]: sys.exit(1)
    
    An exception has occurred, use %tb to see the full traceback.
    
    SystemExit: 1
    
    To exit: use 'exit', 'quit', or Ctrl-D.
    

So, ipython is catching the SystemExit exception. I would suggest using a
different interpreter for this particular job, nice as ipython is.
Alternatively you can use:

    
    
    import os
    os._exit(1)
    

However, this skips all sorts of important cleanup code (e.g. `finally`
blocks) and is generally a Bad Idea.

Edit:

This seems to work. After writing it I can hear some alarm bells in the
distance and there are red flags waving. Not sure what that's about. Anyway,
create a new script `/usr/bin/ipysh` with:

    
    
    #!/usr/bin/python
    
    import sys
    from IPython.core import interactiveshell
    shell = interactiveshell.InteractiveShell()
    shell.safe_execfile(sys.argv[1], {}, raise_exceptions=True,
                        exit_ignore=False)
    

Make that executable, then set your hook's hashbang to `#!/usr/bin/ipysh`.

