ipython、jupyter 在代码执行前修改待执行的代码

编程入门 行业动态 更新时间:2024-10-25 02:26:03

ipython、jupyter 在<a href=https://www.elefans.com/category/jswz/34/1771412.html style=代码执行前修改待执行的代码"/>

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)

上述代码是一个自定义的 CodeTransformerload_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 生成。

然后在配置文件中追加以下配置,我的自定义 CodeTransformerD:/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 在代码执行前修改待执行的代码

本文发布于:2023-12-03 06:49:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1652327.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码   ipython   jupyter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!