Extending Python with C\C++ 实践问题

本文介绍了如何在C/C++中扩展Python,包括处理标准和自定义异常,使用PyErr_Occurred(), PyErr_Clear(), PyArg_ParseTuple()等函数,并探讨了类、对象、方法和属性的相关实践。" 77996865,5698189,Spark WordCount深度解析与实战,"['Spark开发', 'Scala编程', '大数据处理', 'IDEA集成', '分布式计算']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python doc:Extending Python

根据上面的内容,可编写如下程序:

#include <Python.h>

static PyObject *spam_system(PyObject *self, PyObject *args)
{
    const char *command;
    int sts;

    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = system(command);
    return Py_BuildValue("i", sts);

}

static PyMethodDef SpamMethods[] = {
    {
  
  "system",  spam_system, METH_VARARGS,"Execute a shell command."},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC
initspam(void)
{
    Py_InitModule("spam", SpamMethods);
}

利用codeblocks新建工程,编译dll, 具体操作步骤可参考Python之美[从菜鸟到高手]。通过这篇文章,我成功在python里调用到了spam.system(‘ls -s’)。

1 标准异常

阅读python官方文档Extending Python with C\C++后,第二小节是关于异常的,我试着在上面代码中加入异常的语句,如下:

#include <Python.h>

static PyObject *spam_system(PyObject *self, PyObject *args)
{
    const char *command;
    int sts;

    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = system(command);
    if (sts > 0) //添加异常,如果系统没有传入的命令,返回值不为0
    {
        //这里的异常PyExc_ArithmeticError是我随便选的预定义异常对象
        PyErr_SetString(PyExc_ArithmeticError, "something is wrong");
        return NULL;
    }
    return Py_BuildValue("i", sts);

}

static PyMethodDef SpamMethods[] = {
    {
  
  "system",  spam_system, METH_VARARGS,"Execute a shell
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值