如何使用pyximport交互地重新加载cython模块 [英] how to reload a cython module interactively using pyximport

查看:149
本文介绍了如何使用pyximport交互地重新加载cython模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写python代码时,我典型的工作流程是使用交互式提示并执行类似的操作

When writing python code, my typical workflow is to use the interactive prompt and do something like

write function
repeat until working:
  test function
  edit function

一旦我确定一切正常,我将以非交互模式运行代码并收集结果.

Once I'm pretty sure everything's ok, I'll run the code in non-interactive mode and collect the results.

有时功能运行太慢,必须对其进行优化.

Sometimes the functions run a little too slow and must be optimized.

我有兴趣使用cython优化这些慢速功能,但我想保留交互式工作流程,即运行这些功能,进行更改并再次运行它们.

I'm interested in using cython to optimize these slow functions, but I want to keep my interactive workflow, i.e., run the functions, make changes, run them again.

有一种简单的方法吗?

到目前为止,我已经尝试将cython函数放在单独的模块"my_functions.pyx"中:

So far I've tried putting my cython functions in a separate module "my_functions.pyx":

def fun1(int x):
    return x + 130

def fun2(int x):
    return x / 30

然后运行(在提示时)

import pyximport; pyximport.install()
import my_functions as mf
mf.fun1(25)

这是第一次工作,但是我想更改我的cython函数并在同一交互式会话中重新加载它们.

This works the first time, but I want to make changes to my cython functions and reload them in the same interactive session.

运行

import my_functions as mf

完全不更新功能.并运行

doesn't update the functions at all. And running

reload(mf)

给出一个错误: 没有名为my_functions的模块

gives an error: No module named my_functions

唯一有效的方法是退出当前会话,重新启动ipython,然后重新导入模块.但是,这种方式扼杀了交互式运行的好处.

The only thing that works is to quit the current session, restart ipython, and import the module all over again. But this sort of kills the benefits of running interactively.

是否有更好的方法可以通过cython交互地优化功能?

Is there a better way to optimize functions with cython interactively?

如果没有,您能否描述使用cython优化代码的其他方法?

If not, can you describe some other ways to approach optimizing code with cython?

感谢您的帮助.

推荐答案

我在"pyximport.install"函数中发现了一个文献不完善的功能,该功能允许重新加载cython模块.将此功能设置为True后,您可以以交互方式加载/重新加载cython模块,而无需重新启动python.

I found a poorly documented feature in the "pyximport.install" function that allows a cython module to be reloaded. With this feature set to True, you can load/reload your cython modules interactively without having to restart python.

如果您使用以下方法初始化cython模块:

If you initialize your cython module with:

import pyximport
pyximport.install(reload_support=True)
import my_functions as mf

您可以更改cython模块,然后重新加载:

You can make changes to your cython module, and then reload with:

reload(mf)

希望这对某人有用.

这篇关于如何使用pyximport交互地重新加载cython模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆