You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PyO3在Rust应用中调用Python函数失败求助

问题原因与解决方案

核心问题

你当前代码里用的PyModule::new(py, "test_funcs")是创建一个空的新Python模块对象,根本不是加载磁盘上已存在的test_funcs.py文件。这个空模块自然没有你定义的test_func函数,所以才会抛出AttributeError。

修复步骤

1. 替换模块加载方式

把PyModule::new换成PyModule::import,这才是PyO3用来加载本地Python模块的正确API。同时要确保Python解释器能找到你的.py文件:

2. 修改后的Rust代码

MyAppMessage::SecondButton => {
    Python::with_gil(|py| {
        // 获取Python的sys模块
        let sys = PyModule::import(py, "sys").expect("Could not import sys module");
        // 将二进制文件所在目录添加到sys.path,确保能找到test_funcs.py
        let current_dir = std::env::current_dir().expect("Could not get current directory");
        sys.call_method1("append", (current_dir,)).expect("Could not add directory to sys.path");

        // 加载本地已有的test_funcs模块
        let my_module = PyModule::import(py, "test_funcs").expect("Could not load Python module");
        // 获取目标函数
        let _load_json = my_module.getattr("test_func").expect("Could not find Python function");
    });
}

3. 额外检查项

  • 确认test_funcs.py里确实正确定义了test_func,比如:
    def test_func():
        print("Called from Rust")
        return "Success"
    
  • 如果程序运行时的工作目录不是二进制文件所在目录,current_dir()可能无法定位模块,此时可以手动指定模块所在路径,或者把该路径添加到系统环境变量PYTHONPATH中。

内容的提问来源于stack exchange,提问作者Beatdown

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 03:35:08