gpt4 book ai didi

c++ - 使用 C/C++ 的扩展 python 中的 AttributeError

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:26:35 26 4
gpt4 key购买 nike

我在使用简单的 C 文件扩展 python 时遇到问题。

hello.c源码:

#include <Python.h>

static PyObject* say_hello(PyObject* self, PyObject* args)
{
const char* name;

if (!PyArg_ParseTuple(args, "s", &name))
return NULL;

printf("Hello %s!\n", name);

Py_RETURN_NONE;
}

static PyMethodDef HelloMethods[] =
{
{"say_hello", say_hello, METH_VARARGS, "Greet somebody."},
{NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC
inithello(void)
{
(void) Py_InitModule("hello", HelloMethods);
}

设置.py:

from distutils.core import setup, Extension

module1 = Extension('hello', sources = ['hello.c'])

setup (name = 'PackageName',
version = '1.0',
packages=['hello'],
description = 'This is a demo package',
ext_modules = [module1])

我还在文件夹“hello”中创建了空文件“__init__.py”。

调用“python setup.py build”后,我可以导入 hello,但是当我尝试使用 "hello.say_hello()"我遇到错误:

追溯(最近的调用最后): 文件“ ”,第 1 行,位于AttributeError: 'module' 对象没有属性 'say_hello'

如果有人可以帮助我找到解决方案,我将不胜感激。

谢谢

最佳答案

您正在导入包而不是扩展:

$python2 hello_setup.py build
running build
running build_py
# etc.
$cd build/lib.linux-x86_64-2.7/
$ls
hello hello.so
$python
Python 2.7.4 (default, Apr 19 2013, 18:28:01)
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import hello
>>> hello
<module 'hello' from 'hello/__init__.py'>

如果你想导入扩展,hello.so,那么你要么重命名它,要么把它放在包下。在这种情况下,您可以使用 from hello import hello 来导入它:

$mv hello.so hello
$python2
Python 2.7.4 (default, Apr 19 2013, 18:28:01)
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from hello import hello
>>> hello
<module 'hello.hello' from 'hello/hello.so'>
>>> hello.say_hello("World!")
Hello World!!

我看不出有一个包只包含一个扩展模块的原因。我会使用更简单的设置简单地摆脱包:

from distutils.core import setup, Extension

module1 = Extension('hello', sources=['hello.c'])

setup(name='MyExtension',
version='1.0',
description='This is a demo extension',
ext_modules=[module1])

这只会生成 hello.so 库,您只需执行以下操作即可:

>>> import hello

导入扩展。

一般建议:避免有多个同名模块/包。有时很难分辨导入了哪个模块(如您的情况)。此外,当使用不同的名称而不是导入错误的模块并出现奇怪的错误时,如果出现问题,您将看到一个 ImportError,它会指出到底缺少什么。

关于c++ - 使用 C/C++ 的扩展 python 中的 AttributeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18464017/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com