卡在 PyObject_GetAttrString() :如何从我的 C++ 代码中获取我的 Python 函数脚本

Stuck at PyObject_GetAttrString() : How to get my Python function script from my C++ code

我的问题是我无法从我的 C++ 脚本上的 Python 脚本中获取函数。

我使用 Python/C API 而我的 IDE 是 VScode。当我 运行 代码时,它停在调用 PyObject_GetAttrString()

的特定行

VScode 的 task.json 中的这一行用于构建我的代码:g++ -IC:/Users/Martin/AppData/Local/Programs/Python/Python37-32/libs/python37.a main.cpp -LC:/Users/Martin/AppData/Local/Programs/Python/Python37-32/libs-lpython37

这行到 运行 它:.\a.exe(.exe 由 VScode 自动创建)

这是我第一次尝试通过 C++ 代码使用 Python 代码。我已经在论坛和其他关于 Whosebug 的主题上进行了搜索,但毕竟我试过了,我还是不明白。 这是代码:

C++ 代码:main.cpp(我执行)

#include <iostream>
#include "C:/Users/Martin/AppData/Local/Programs/Python/Python37-32/include/Python.h"
using namespace std;

int main ()
{
    cout << "Start \n";
    
    Py_Initialize();
    cout << "2\n";  PyObject* my_module = PyImport_ImportModule("mat");
    cout << "3\n";  PyObject* my_function = PyObject_GetAttrString(my_module,"getfive");
    cout << "4\n";  PyObject* my_result = PyObject_CallObject(my_function,NULL);
    cout << "5\n";  double result = PyFloat_AsDouble(my_result);
    cout << "6\n";  printf("My result is :  %f",result);
    cout << "7\n";
    Py_Finalize();

    return 0;
}

Python 代码:mat.py

def getfive():
    print "python say 5 !"
    return 5

def speak():
    print "speak"

输出我除了有:

Start 1
2
3 
python say 5!
4
5
6
My result is :  5
7

输出我真的有:

Start 1
2
3

我真的不明白为什么它在这一行不起作用:“PyObject* my_function = PyObject_GetAttrString(my_module,”speak”); “

感谢您阅读到这里,如果您能回答我,我会做得更多!

问题是我的 python 代码是错误的:我没有把 () 放到我的 print 行中......非常基本,但我们必须小心我们的 python 代码,错误可能来自那里!

我使用了 PyErr_Print(); ,这使我们能够获得有关错误和异常的特定输出,您可以从 python 代码中获得! (那里有更多信息:https://docs.python.org/3/c-api/exceptions.html

非常感谢 Wim Lavrijsen 帮助我澄清我的问题!

这是现在有效的正确代码:

C++代码(main.cpp):

#include <iostream>
#include "C:/Users/Martin/AppData/Local/Programs/Python/Python37-32/include/Python.h"

using namespace std;

int main ()
{
    cout << "Start 1 \n";

    Py_Initialize();
    cout << "2\n";  PyObject* my_module = PyImport_ImportModule("mat");
    cerr << my_module << "\n";
    PyErr_Print();
    cout << "3\n";  PyObject* my_function = PyObject_GetAttrString(my_module,"getfive");
    cout << "4\n";  PyObject* my_result = PyObject_CallObject(my_function,NULL);
    cout << "5\n";  int result = _PyLong_AsInt(my_result);
    cout << "6\n";  printf("My result is :  %d", result);
    cout << "\n7\n";
    Py_Finalize();
    return 0;
}

Python代码(mat.py):

def getfive():
    print("python say 5 !")
    return 5

def speak():
    print(speak)

我得到的错误:

SyntaxError: Missing parentheses in call to 'print'. Did you mean print("python say 5 !")?
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("speak")?

以及我想要的输出

Start 1 
2
0x790600
3
4
python say 5 !
5
6
My result is :  5
7

结论:当您使用 te Python/C API 时,请使用 PyErr_Print() 检查 Python 代码 !