IPython - shell命令失败时引发异常 [英] IPython - Raise exception when a shell command fails

查看:1292
本文介绍了IPython - shell命令失败时引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用将IPython作为系统外壳

当shell命令失败时,有没有办法让IPython引发异常? (非零退出代码)

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.

推荐答案

IPython 4.0.1开始,!cmd 转换为 get_ipython( ).system(repr(cmd)) IPython.core.inputtransformer._tr_system())。
在源代码中,它实际上是 InteractiveShell.system_raw(),因为 inspect.getsourcefile() inspect.getsource()可以告诉。

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.

它委托给 os.system()< Windows中的/ code>和其他操作系统中的 subprocess.call()。不可配置,正如您从代码中看到的那样。

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

因此,您需要将其替换为可调用 subprocess.check_call()<的内容。 / code>。

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

除了手工修补猴子外,这可以通过 IPython配置系统。可用选项(使用%config 魔法查看)不允许用另一个类替换 TerminalInteractiveShell 但是几个 TerminalIPythonApp 选项允许在启动时执行代码。

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.

请仔细检查您是否确实需要这样做: system_raw()的来源显示它设置 _exit_code 变量 - 因此它实际上不会失败完全默默地。

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.

这篇关于IPython - shell命令失败时引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆