IPython - 当 shell 命令失败时引发异常

IPython - Raise exception when a shell command fails

我正在使用 IPython as a system shell

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

默认设置使它们静默失败。

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

它在 Windows 中委托给 os.system(),在其他操作系统中委托给 subprocess.call()。不可配置,从代码中可以看出。

因此,您需要将其替换为可以调用 subprocess.check_call().

的内容

除了手动修补猴子外,还可以使用 IPython configuration system 来完成。可用选项(可使用 %config 魔法查看)不允许将 TerminalInteractiveShell 替换为另一个 class 但几个 TerminalIPythonApp 选项允许在启动时执行代码。

请仔细检查你是否真的需要这个:查看 system_raw() 的源代码会发现它设置了 _exit_code 变量 - 所以它实际上并没有失败 完全默默

如果您使用 ! 执行 shell 命令,错误将自动通过

!echo "hello" && exit 1
hello

如果使用%%sh单元格魔法执行shell命令,会出现错误:

%%sh
echo "hello" && exit 1
hello
---------------------------------------------------------------------------
CalledProcessError                        Traceback (most recent call last)
<ipython-input-10-9229f76cae28> in <module>
----> 1 get_ipython().run_cell_magic('sh', '', 'echo "hello" && exit 1\n')

~/anaconda/envs/altair-dev/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
   2360             with self.builtin_trap:
   2361                 args = (magic_arg_s, cell)
-> 2362                 result = fn(*args, **kwargs)
   2363             return result
   2364 

~/anaconda/envs/altair-dev/lib/python3.6/site-packages/IPython/core/magics/script.py in named_script_magic(line, cell)
    140             else:
    141                 line = script
--> 142             return self.shebang(line, cell)
    143 
    144         # write a basic docstring:

<decorator-gen-110> in shebang(self, line, cell)

~/anaconda/envs/altair-dev/lib/python3.6/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188 
    189         if callable(arg):

~/anaconda/envs/altair-dev/lib/python3.6/site-packages/IPython/core/magics/script.py in shebang(self, line, cell)
    243             sys.stderr.flush()
    244         if args.raise_error and p.returncode!=0:
--> 245             raise CalledProcessError(p.returncode, cell, output=out, stderr=err)
    246 
    247     def _run_script(self, p, cell, to_close):

CalledProcessError: Command 'b'echo "hello" && exit 1\n'' returned non-zero exit status 1.