Check the exit status of last command in ipython

不羁岁月 提交于 2021-02-07 13:15:38

问题


Does anybody know how to check the status of the last executed command (exit code) in ipython?


回答1:


I assume that you are talking about running commands from IPython using the ! escape:

In[1]: !echo hello
hello

In[2]:

Using Google I found the documentation and there is no mention of the exit status of the command being captured anywhere. Using dir() I looked for a variable name that might be holding that information and I didn't find anything. I tried the x = !ls syntax and x gets set to a list of output lines from the command; there is no exit status in there.

In short, I don't think IPython is even capturing this information. At this point I would want to check the source code to IPython to try to figure out anything else.

You can always just run the command with os.system() and get an exit status from that.

In[1]: !launch_eva
launch_eva: could not open AT Field

In[2]: import os
In[3]: exit_status = os.system("launch_eva")
launch_eva: could not open AT Field

In[4]: exit_status
3

In[5]:

Thus we see the command launch_eva is returning exit status 3 when it can't open an AT Field.

It seems like this is something that IPython should be saving. There are plenty of little hidden variables. You should file a feature request about this.

NOTE: This was tested in IPython 0.10.1 on Ubuntu. Another answer, by "piotr", says that exit code will be captured in IPython 0.11, due to release soon. I cloned the source code from the Git repository at https://github.com/ipython/ipython.git and tested it with python ipython.py; as piotr said, the exit status is saved in a variable called _exit_status.




回答2:


It should be stored as _exit_code after you run the command (at least in the upcoming v0.11 release).




回答3:


You can store the command result in variable and you can check the variable whether it is present in locals() function or not. for example1:-

var1="hello"
if 'var1' in locals():
print "status is false i.e 0"
else :
print "status is false i.e 1"

In this case the variable will be printed as hello, if you will not assign var1 to any value it will go to else loop. example2:-

var1=subprocess.check_output('ps -aef | grep -i dmesg -wT | grep -v grep',shell=True)
if 'var1' in locals():
print "status is true i.e 0"
else :
print "status is false i.e 1"


来源:https://stackoverflow.com/questions/6755794/check-the-exit-status-of-last-command-in-ipython

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