代码执行前修改待执行的代码"/>
ipython、jupyter 在代码执行前修改待执行的代码
ipython、jupyter 在代码执行前修改待执行的代码
- 代码
- 配置
- 测试
假设有一个需求,需要把待执行代码中的所有 root 替换成 tom。
代码
可以通过自定义 ipython 的 input transformation 来实现这个需求,官方文档 Custom input transformation — IPython 8.16.0 documentation
class CodeTransformer(object):def __init__(self, ip):self.shell = ipdef replace(self, lines):new_lines = []# 按行操作for line in lines:# 将 root 替换成 tomnew_lines.append(line.replace('root', 'tom'))return new_lines# 加载 ipython 扩展
def load_ipython_extension(ip):ct = CodeTransformer(ip)ip.input_transformers_post.append(ct.replace)
上述代码是一个自定义的 CodeTransformer
,load_ipython_extension()
方法可以将其当做一个扩展加载进 ipython。
配置
我们需要在 ipython 的配置文件中添加配置,这次才能在 ipython 启动时自动加载我自定义的 CodeTransformer
。
ipython 默认配置文件在用户目录的 .python/profile_default 文件夹中,比如我的是 C:/Users/zhaobs/.ipython/profile_default/ipython_config.py。如果没有 ipython_config.py
文件,可以执行 ipython profile create
生成。
然后在配置文件中追加以下配置,我的自定义 CodeTransformer
在 D:/custom_code_transformer.py 文件中,所以需要把 D:/ 添加到 python 的模块搜索路径中,custom_code_transformer 是模块名(py 文件的文件名前缀)
import sys
sys.path.append('D:/')
c.InteractiveShellApp.extensions.append('custom_code_transformer')
测试
从下图中可以看出,root 没替换成了 tom,而其他的没受影响
更多推荐
ipython、jupyter 在代码执行前修改待执行的代码
发布评论