IPython - Raise exception when a shell command fails

孤者浪人 提交于 2019-12-12 03:56:17

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/35857230/ipython-raise-exception-when-a-shell-command-fails

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!