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

基于Rust PyO3执行含未知模块导入的Python脚本方法问询

在Rust中通过PyO3调用依赖未知的Python模块函数

我希望通过Rust调用Python模块中的函数,但该模块的导入依赖在编码阶段是未知的。

待执行Python文件示例

import testmod

def main():
    print("Hello World!")
    testmod.test_fun()
    return 0

我想找到一种将文件传入PyO3并让其自动解析导入所有依赖的方法,这类功能似乎应该属于PyO3,但我没找到相关文档。

当前使用的Rust代码(无法正常工作)

pub fn python(args: &WatchCommand) -> PyResult<()> {
    let main = std::fs::canonicalize(&args.main)?;
    let parent = main.parent().unwrap();
    debug!("Loading Python Module...");
    // Load file contents
    let file_contents = std::fs::read_to_string(&args.main)?;
    // Run Python Code
    Python::with_gil(|py| -> PyResult<()> {
        // Load modules in the same folder
        debug!("Search Folder: {:?}", parent);
        for entry in WalkDir::new(&parent) {
            match entry {
                Ok(res) => {
                    if res.path().is_file() && res.path().extension().unwrap_or_default() == "py" {
                        debug!("Loading module: {:?}", res.path());
                        let file_content = std::fs::read_to_string(res.path())?;
                        let name = res.path().file_stem().unwrap().to_str().unwrap();
                        PyModule::from_code(py, &file_content, name, name)?;
                    }
                }
                Err(e) => error!("Error loading module: {}", e),
            }
        }
        let main = PyModule::from_code(py, &file_contents, "main.py", "main");
        // Build arguments
        let args = ();
        // let kwargs = [("slope", 0.2)].into_py_dict(py);clap
        let result: i16 = main?.getattr("main")?.call(args, None)?.extract()?;
        Ok(())
    })
}

执行后错误输出

DEBUG Loading Python Module...
DEBUG Search Folder: "..."
DEBUG Loading module: "...\main.py"
ERROR Error running python code: ModuleNotFoundError: No module named 'testmod'

恳请各位提供帮助。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 10:37:48