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

在C++中调用Python代码时遭遇ModuleNotFoundError: No module named 'sender'

问题:C++调用Python脚本时触发ModuleNotFoundError: No module named 'sender'

编译C++代码过程正常,但运行时提示找不到名为sender的Python模块,同时代码还存在函数调用不匹配的问题。以下是相关代码及编译命令:

Python代码(sender.py)

import smtplib
from email.mime.text import MIMEText

def send_email(recipient_email, passw):
    sender = "sender2023@gmail.com"
    password = "rkmwruhqnsv"

    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()

    message = "You requested password recovery in our taxi service.\nYour new password: " + passw

    try:
        server.login(sender, password)
        msg = MIMEText(message)
        msg["Subject"] = "Password Recovery"
        server.sendmail(sender, recipient_email, msg.as_string())

        return "The message was sent successfully!"
    except Exception as _ex:
        return f"{_ex}\nCheck your login or password please!"

C++代码(run.cpp)

#include <Python.h>

int main(){
    Py_Initialize();

    PyObject* module = PyImport_ImportModule("sender");
    if (!module){
        PyErr_Print();
        return 1;
    }

    const char* mail = "example@gmail.com";
    const char* password = "zxc4143grl";

    PyObject* function = PyObject_GetAttrString(module, "main");
    if (!function || !PyCallable_Check(function)){
        PyErr_Print();
        return 1;
    }

    PyObject* args = Py_BuildValue("(ss)", mail, password);
    PyObject* return_value = PyObject_CallObject(function, args);
    if (!return_value){
        PyErr_Print();
        return 1;
    }

    Py_DECREF(args);
    Py_DECREF(function);
    Py_DECREF(module);

    Py_Finalize();

    return 0;
}

编译命令

g++ -I/usr/include/python3.10 run.cpp -o main -lpython3.10

解决方案

1. 解决ModuleNotFoundError问题

Python解释器找不到sender.py,是因为脚本所在目录不在Python的搜索路径中,可通过以下两种方式解决:

  • 方式一:移动脚本位置
    将sender.py直接放到C++编译生成的main可执行文件的同一目录下,运行时Python就能自动找到该模块。
  • 方式二:在C++中手动添加脚本路径
    在Py_Initialize()之后,添加代码将脚本所在目录加入Python的sys.path:
    // 获取Python的sys.path对象
    PyObject* sysPath = PySys_GetObject((char*)"path");
    // 替换为你的sender.py所在的实际目录路径
    PyList_Append(sysPath, PyUnicode_FromString("/home/yourname/scripts/"));
    

2. 修复函数调用不匹配问题

C代码中尝试调用Python模块里的main函数,但Python脚本中定义的函数是send_email,需修改C代码中的函数名:

// 把"main"改为"send_email"
PyObject* function = PyObject_GetAttrString(module, "send_email");

完成以上修改后,重新编译运行即可正常调用Python脚本发送邮件。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 15:55:17