我为我的CPython扩展编写了以下代码:
#include <Python.h>
static PyObject *greeting(PyObject* self)
{
return Py_BuildValue("s" , "Hello python modules!!!");
}
static char *my_docstring = "This is a sample docstring";
static PyMethodDef greeting_funcs[] = {
{"greeting" , (PyCFunction)greeting , METH_NOARGS , my_docstring} , {NULL}
};
void initModule(void){
Py_InitModule3("greeting" , greeting_funcs , "Module example!!!");
}当我在IPython3 shell中执行以下操作时
from setuptools import setup , Extension
modules = [Extension('mod', sources=["/home/spm/python_module/mod.c"])]
setup(ext_modules=modules) 我知道错误:
SystemExit: usage: ipython3 [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts]
or: ipython3 --help [cmd1 cmd2 ...]
or: ipython3 --help-commands
or: ipython3 cmd --help
error: no commands supplied任何帮助都是非常感谢的。
谢谢。
发布于 2020-02-29 19:31:16
首先,您的mod.c不会编译。Py_InitModule3在Python3中被删除;您必须创建一个PyModuleDef结构并添加一个名为PyInit_{library name}的init函数,该函数将PyModuleDef引用传递给PyModule_Create以初始化模块:
#include <Python.h>
#define MY_DOCSTRING "This is a sample docstring"
static PyObject *greeting(PyObject* self)
{
return Py_BuildValue("s" , "Hello python modules!!!");
}
static PyMethodDef greeting_funcs[] = {
{"greeting" , (PyCFunction)greeting , METH_NOARGS , MY_DOCSTRING} , {NULL}
};
// python module definition
static struct PyModuleDef greetingModule = {
PyModuleDef_HEAD_INIT, "greeting", "Module example!!!", -1, greeting_funcs
};
// register module namespace
PyMODINIT_FUNC PyInit_mod(void)
{
PyObject *module;
module = PyModule_Create(&greetingModule);
if (module == NULL)
return NULL;
return module;
},当我在IPython3 shell中执行以下操作时,就会得到错误
此代码通常不从IPython调用。它被放入一个名为setup.py的脚本中,然后从终端执行,提供setup函数应该调用的任务。
$ python setup.py build_ext --inplace以构建扩展模块并将其放置到当前目录中。
当然,您也可以在IPython中模仿这一点:
In [1]: import sys
In [2]: sys.argv.extend(["build_ext", "--inplace"])
In [3]: from setuptools import setup, Extension
In [4]: modules = [Extension('mod', sources=["mod.c"])]
In [5]: setup(ext_modules=modules)
running build_ext
...
In [6]: sys.argv = sys.argv[:1]但是,更好的解决方案是将安装代码写入setup.py脚本。然后,您可以通过IPython魔术在%run中执行它:
In [1]: %run setup.py build_ext --inplace
running build_ext
building 'mod' extension
...https://stackoverflow.com/questions/60441209
复制相似问题