5

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I am aware that it is catching the non-zero exit code. I'm trying to see if anyone has got around this issue. (The bang syntax is so nice! I'm sure there's someone out there that has tried to shell script with ipython!)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.