【问题标题】:Using the python api in c not working on mac在c中使用python api在mac上不起作用
【发布时间】:2017-08-14 18:23:40
【问题描述】:

我正在尝试导入与 main.c 文件位于同一目录中的 python 文件,但由于某种原因它无法正常工作。我在 PyImport_ImportModule('dizzle') 上一直失败。任何帮助将不胜感激我在 Mac 上(*我可以让它在 Ubuntu 上工作,这很奇怪)我设置了 PYTHONPATH。

mytestfolder 
   main.c
   dizzle.py

这是我的 main.c

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <Python/Python.h>

int main()
{ 
  char *xx = getpimacaddress2();
  printf("%s", xx);

}

char *getpimacaddress2()
{



    Py_Initialize();


    PyObject* module = PyImport_ImportModule("dizzle");
    assert(module != NULL);

    PyObject* klass = PyObject_GetAttrString(module, "SnowTest");
    assert(klass != NULL);

    PyObject* instance = PyInstance_New(klass, NULL, NULL);
    assert(instance != NULL);

    PyObject* result = PyObject_CallMethod(instance, "add_test", "(ii)", 10, 34);
    assert(result != NULL);

    Py_Finalize();

    return PyString_AsString(result);
}

Python 文件dizzle.py

class SnowTest:

  def add_test(self, x, y):
    z = x + y 
    return str(z)

【问题讨论】:

  • 怎么会失败?
  • 在我的第一个断言中,我认为这是由于它没有在当前目录中找到我的模块@Vallentin
  • 您记得将路径PyObject *path = PyObject_GetAttrString(PyImport_ImportModule("sys"), "path")PyList_Append(path, ...) 取为您应用程序的当前工作目录吗?
  • 检查是否设置了异常(如果有)if(PyErr_Occurred()) PyErr_Print();
  • 我尝试了你的建议,但我仍然收到断言失败:(module != NULL) @Vallentin

标签: python c python-2.7


【解决方案1】:

我能够重现问题。但是请注意,我是在 Windows 上这样做的。解决方案应该是一样的。我在 cmets 中提到它可能与 sys.path 有关。测试后实际上是哪个问题。

在调用Py_Initialize() 之后立即执行以下操作:

PyObject *sys = PyImport_ImportModule("sys");
PyObject *path = PyObject_GetAttrString(sys, "path");
PyList_Append(path, PyUnicode_FromString("..."));

您将... 替换为检索应用程序当前工作目录(在您的情况下是包含dizzle.py 文件的目录)的位置。

您也可以查看:

PyRun_SimpleString("print(os.getcwd())");

如果它打印你应用程序的当前工作目录,那么你同样可以在调用Py_Initialize()之后直接执行以下操作:

PyRun_SimpleString("sys.path.append(os.getcwd())");

其中任何一个都让assert(module != NULL) 通过。

如果它确实与PYTHONPATH 有关(我根据您的错误对此表示怀疑)。然后你可以使用Py_SetPythonHome(L"/path/to/python")

【讨论】:

    猜你喜欢
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    相关资源
    最近更新 更多