mkn*_*cht 6 python ipython ipython-magic
我想默认修改IPython如何处理导入错误.当我在IPython shell中对原型进行原型化时,我通常会忘记首先导入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
Run Code Online (Sandbox Code Playgroud)
当然,这是我的错,因为有坏习惯,当然,在一个有意义的脚本或真正的程序中,但在shell中我宁愿IPython遵循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
Run Code Online (Sandbox Code Playgroud)
如果使用vanilla IPython无法做到这一点,我需要做些什么来使其工作?是包装内核前进的最简单的方法?或者应该使用魔术命令直接在核心中实现?
请注意,这是从不同的各种问题,其中有人要始终加载预先定义的模块.我不.因为我不知道我将要做什么,而且我不想加载所有东西(我也不想保持所有更新的列表.
Aar*_*sen 11
注意:现在正在Github上维护.从那里下载最新版本的脚本!
我开发了一个脚本,它绑定到IPython的异常处理set_custom_exc.如果有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)
Run Code Online (Sandbox Code Playgroud)
启动IPython提示时,可以通过将其保存到某个位置然后设置一个名PYTHONSTARTUP为此文件路径的环境变量来自动运行.您可以根据操作系统设置不同的环境变量(请记住更改路径):
setx PYTHONSTARTUP C:\startup.py在命令提示符下export PYTHONSTARTUP=$HOME/startup.py你的~/.bashrc这是脚本的实际演示:

| 归档时间: |
|
| 查看次数: |
376 次 |
| 最近记录: |