Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IPython - Raise exception when a shell command fails

Tags:

ipython

I'm using IPython as a system shell.

Is there a way to make IPython to raise an exception when the shell command fails? (non-zero exit codes)

The default makes them fail silently.

like image 657
130333 Avatar asked Apr 11 '26 23:04

130333


1 Answers

As of IPython 4.0.1, !cmd is transformed into get_ipython().system(repr(cmd)) (IPython.core.inputtransformer._tr_system()). In the source, it's actually InteractiveShell.system_raw(), as inspect.getsourcefile() and inspect.getsource() can tell.

It delegates to os.system() in Windows and subprocess.call() in other OSes. Not configurable, as you can see from the code.

So, you need to replace it with something that would call subprocess.check_call().

Apart from monkey-patching by hand, this can be done with the IPython configuration system. Available options (viewable with the %config magic) don't allow to replace TerminalInteractiveShell with another class but several TerminalIPythonApp options allow to execute code on startup.

Do double-check whether you really need this though: a look through the system_raw()'s source reveals that it sets the _exit_code variable - so it doesn't actually fail completely silently.

like image 194
ivan_pozdeev Avatar answered Apr 14 '26 13:04

ivan_pozdeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!