[英]IPython scripting - Exit script with status code
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).我正在尝试使用 ipython 来编写 git pre-commit 钩子的脚本,因为它有一个很好的语法来运行 shell 命令并将标准输出结果转换为字符串列表(这便于处理)。
I need to return a status code != 0 from the ipython script so that git pre-commit hook will abort the commit.我需要从 ipython 脚本返回一个状态代码 != 0 以便 git pre-commit hook 将中止提交。
Consider this example script考虑这个示例脚本
#! /bin/ipython
import sys
sys.exit(1)
running it from the shell从 shell 运行它
$ ipython test.ipy
but then checking the status code with $ echo $?
但是然后用
$ echo $?
检查状态代码$ echo $?
always returns 0
总是返回
0
Is there a way to make ipython return a non-zero status code?有没有办法让 ipython 返回非零状态代码?
Open up ipython and try running that code interactively.打开 ipython 并尝试以交互方式运行该代码。
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.因此,ipython 正在捕获 SystemExit 异常。 I would suggest using a different interpreter for this particular job, nice as ipython is.
我建议为这个特定的工作使用不同的解释器,就像 ipython 一样好。 Alternatively you can use:
或者,您可以使用:
import os
os._exit(1)
However, this skips all sorts of important cleanup code (eg finally
blocks) and is generally a Bad Idea.然而,这会跳过各种重要的清理代码(例如
finally
块)并且通常是一个坏主意。
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/ipysh
:
#!/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
.制作该可执行文件,然后将钩子的 hashbang 设置为
#!/usr/bin/ipysh
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.