让IPython明白我的意思
我想修改默认情况下IPython处理导入错误的方式。当我在IPython shell中创建原型时,通常会忘记首先导入让IPython明白我的意思,python,ipython,ipython-magic,Python,Ipython,Ipython Magic,我想修改默认情况下IPython处理导入错误的方式。当我在IPython shell中创建原型时,通常会忘记首先导入os、re或任何我需要的东西。前几个语句通常遵循以下模式: In [1]: os.path.exists("~/myfile.txt") --------------------------------------------------------------------------- NameError Trace
os
、re
或任何我需要的东西。前几个语句通常遵循以下模式:
In [1]: os.path.exists("~/myfile.txt")
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-0ffb6014a804> in <module>()
----> 1 os.path.exists("~/myfile.txt")
NameError: name 'os' is not defined
In [2]: import os
In [3]: os.path.exists("~/myfile.txt")
Out[3]: False
[1]中的:os.path.exists(“~/myfile.txt”)
---------------------------------------------------------------------------
NameError回溯(最近一次呼叫上次)
在()
---->1 os.path.exists(“~/myfile.txt”)
NameError:未定义名称“os”
在[2]中:导入操作系统
在[3]中:os.path.exists(“~/myfile.txt”)
Out[3]:False
当然,这是我的错,因为我有坏习惯,
当然,在有意义的脚本或真实程序中,
但实际上,我更希望伊普顿遵循
DWIM原则,通过至少尝试导入我尝试使用的内容
In [1]: os.path.exists("~/myfile.txt")
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-0ffb6014a804> in <module>()
----> 1 os.path.exists("~/myfile.txt")
NameError: name 'os' is not defined
Catching this for you and trying to import "os" … success!
Retrying …
---------------------------------------------------------------------------
Out[1]: False
[1]中的:os.path.exists(“~/myfile.txt”)
---------------------------------------------------------------------------
NameError回溯(最近一次呼叫上次)
在()
---->1 os.path.exists(“~/myfile.txt”)
NameError:未定义名称“os”
为您捕获此信息并尝试导入“os”…成功!
重试…
---------------------------------------------------------------------------
Out[1]:False
如果香草IPython不能做到这一点,我该怎么办
让这一切顺利吗?这是最简单的前进之路吗?还是应该直接在内核中用一个神奇的命令来实现
注意,这与人们希望始终加载预定义模块的情况不同。我不。因为我不知道我将要处理什么,我不想加载所有内容(也不想更新所有内容的列表)。注意:现在正在维护此脚本。从那里下载最新版本的脚本 我开发了一个脚本,它通过
set\u custom\u exc
绑定到IPython的异常处理。如果出现NameError
,它会使用正则表达式查找您尝试使用的模块,然后尝试导入它。然后它会运行您尝试再次调用的函数。代码如下:
import sys, IPython, colorama # <-- colorama must be "pip install"-ed
colorama.init()
def custom_exc(shell, etype, evalue, tb, tb_offset=None):
pre = colorama.Fore.CYAN + colorama.Style.BRIGHT + "AutoImport: " + colorama.Style.NORMAL + colorama.Fore.WHITE
if etype == NameError:
shell.showtraceback((etype, evalue, tb), tb_offset) # Show the normal traceback
import re
try:
# Get the name of the module you tried to import
results = re.match("name '(.*)' is not defined", str(evalue))
name = results.group(1)
try:
__import__(name)
except:
print(pre + "{} isn't a module".format(name))
return
# Import the module
IPython.get_ipython().run_code("import {}".format(name))
print(pre + "Imported referenced module \"{}\", will retry".format(name))
except Exception as e:
print(pre + "Attempted to import \"{}\" but an exception occured".format(name))
try:
# Run the failed line again
res = IPython.get_ipython().run_cell(list(get_ipython().history_manager.get_range())[-1][-1])
except Exception as e:
print(pre + "Another exception occured while retrying")
shell.showtraceback((type(e), e, None), None)
else:
shell.showtraceback((etype, evalue, tb), tb_offset=tb_offset)
# Bind the function we created to IPython's exception handler
IPython.get_ipython().set_custom_exc((Exception,), custom_exc)
import sys,IPython,colorama#目前,这个脚本无限循环出现一些错误-如果导入导致namererror,清理例程执行相同的导入…-您已经知道发生了什么。您需要检查您试图导入的模块是否存在。@Rogalski我该怎么做?我知道pip
有方法来执行此操作,但有人正在尝试导入可能正在导入他们本地计算机上的某些内容。运行:尝试:导入除ImportError之外的任何内容:oops\u失败\u导入\u处理它()
?@Rogalski谢谢,我正在更新它以支持此功能,并具有更清晰的输出。@Rogalski此功能现在已更新,看起来更漂亮,而不是无限循环。