一、Python和C扩展

cPython是C编写的,python的扩展可以用C来写,也便于移植到C++.

编写的Python扩展,需要编译成一个.so的共享库。

Python程序中。

官方文档:https://docs.python.org/2/extending/extending.html#writing-extensions-in-c

二、举例

>>> import spam
>>> status = spam.system("ls -l")

 我们需要创建一个spam.c的文件模块,这个模块是C实现。开头必须有

  #include <Python.h>

 下面实现以上的举子:

static PyObject *
spam_system(PyObject *self, PyObject *args)
{
const char *comment;
int sts; if (!PyArg_ParseTuple(args, "s", &command))
return NULL;
sts = system(command);
return Py_BuildValue("i", sts);
}

上述函数的Python扩展中C函数有两个参数:self, args,这两个是必须的。

三、模块方法和函数初始化

1、定义模块及帮助文档。模块叫system,指定执行函数spam_system, 帮助文档“Execute a shell command”

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

在编译完之后,导入模块,执行如下help命令,就会出现文档

In []: help(spam)

Help on module spam:

NAME
spam FILE
/usr/lib/python2./site-packages/spam.so FUNCTIONS
system(...)
Execute a shell command.

2、初始spam,初始化模块函数一定要init[module],保持一致

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

三、编译

1、编译模块时,需要编写setup.py文件

#!/usr/bin/env python
# -*- coding: utf-8 -*- from distutils.core import setup, Extension MOD = "spam"
setup(name=MOD, ext_modules=[Extension(MOD, sources=['spam.c'])])

模块名name和扩展模块。

2、进行编译

[root@local PycExt]# python setup.py build
running build
running build_ext
building 'spam' extension
gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 -march=i686 -mtune=atom -fasynchronous-unwind-tables -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 -march=i686 -mtune=atom -fasynchronous-unwind-tables -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/usr/include/python2.6 -c spam.c -o build/temp.linux-i686-2.6/spam.o
In file included from /usr/include/python2.6/pyconfig.h:4,
from /usr/include/python2.6/Python.h:8,
from spam.c:3:
/usr/include/python2.6/pyconfig-32.h:1034:1: warning: "_POSIX_C_SOURCE" redefined
In file included from /usr/include/stdio.h:28,
from spam.c:1:
/usr/include/features.h:162:1: warning: this is the location of the previous definition
In file included from /usr/include/python2.6/pyconfig.h:4,
from /usr/include/python2.6/Python.h:8,
from spam.c:3:
/usr/include/python2.6/pyconfig-32.h:1043:1: warning: "_XOPEN_SOURCE" redefined
In file included from /usr/include/stdio.h:28,
from spam.c:1:
/usr/include/features.h:164:1: warning: this is the location of the previous definition
gcc -pthread -shared build/temp.linux-i686-2.6/spam.o -L/usr/lib -lpython2.6 -o build/lib.linux-i686-2.6/spam.so

生成一个build的文件夹,里面有spam.so库

[root@local PycExt]# ls
build setup.py spam.c

3、安装

[root@local PycExt]# python setup.py install
running install
running build
running build_ext
running install_lib
copying build/lib.linux-i686-2.6/spam.so -> /usr/lib/python2.6/site-packages
running install_egg_info
Removing /usr/lib/python2.6/site-packages/spam-0.0.0-py2.6.egg-info
Writing /usr/lib/python2.6/site-packages/spam-0.0.0-py2.6.egg-info

执行命令如上,就安装好了。

四、使用模块

In [1]: import spam

In [2]: spam.system("ls -la")
total 20
drwxr-xr-x. 3 root root 4096 Apr 8 22:07 .
drwxr-xr-x. 10 root root 4096 Apr 8 21:01 ..
drwxr-xr-x. 4 root root 4096 Apr 8 21:51 build
-rw-r--r--. 1 root root 171 Apr 8 21:48 setup.py
-rw-r--r--. 1 root root 549 Apr 8 22:07 spam.c
Out[2]: 0 In [3]:

如上,即为python扩展相关内容...

spam.c

#include <stdio.h>
#include <stdlib.h>
#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, , NULL}
}; void initspam() {
Py_InitModule("spam", SpamMethods);
} int main(int argc, char *argv[])
{
return ;
}

setup.py

#!/usr/bin/env python
# -*- coding: utf-8 -*- from distutils.core import setup, Extension MOD = "spam"
setup(name=MOD, ext_modules=[Extension(MOD, sources=['spam.c'])])

Python和C扩展实现方法的更多相关文章

  1. python获取文件扩展名的方法(转)

    主要介绍了python获取文件扩展名的方法,涉及Python针对文件路径的相关操作技巧.具体实现方法如下: 1 2 3 4 import os.path def file_extension(path ...

  2. python获取文件扩展名的方法

    主要介绍了python获取文件扩展名的方法,涉及Python针对文件路径的相关操作技巧 import os.path def file_extension(path): ] print file_ex ...

  3. sqlalchemy mark-deleted 和 python 多继承下的方法解析顺序 MRO

    sqlalchemy mark-deleted 和 python 多继承下的方法解析顺序 MRO 今天在弄一个 sqlalchemy 的数据库基类的时候,遇到了跟多继承相关的一个小问题,因此顺便看了一 ...

  4. python类:magic魔术方法

    http://blog.csdn.net/pipisorry/article/details/50708812 魔术方法是面向对象Python语言中的一切.它们是你可以自定义并添加"魔法&q ...

  5. (转)python类:magic魔术方法

    原文:https://blog.csdn.net/pipisorry/article/details/50708812 版权声明:本文为博主皮皮http://blog.csdn.net/pipisor ...

  6. python使用C扩展

    CPython还为开发者实现了一个有趣的特性,使用Python可以轻松调用C代码 开发者有三种方法可以在自己的Python代码中来调用C编写的函数-ctypes,SWIG,Python/C API.每 ...

  7. openresty 学习笔记番外篇:python的一些扩展库

    openresty 学习笔记番外篇:python的一些扩展库 要写一个可以使用的python程序还需要比如日志输出,读取配置文件,作为守护进程运行等 读取配置文件 使用自带的ConfigParser模 ...

  8. 使用pybind11为Python编写C++扩展(一)配置篇:Build(编译和链接)

    目录 Setuptools CMake 最后决定选用pybind11,理由如下: 比python原生的C API看起来人性多了 我的C++代码不是现成的,需要一定的C++开发工作量,所以感觉cytho ...

  9. jquery 扩展插件方法

    分析插件jquery.countdown.js (function($) { $.fn.countdown = function(options) { // default options var d ...

随机推荐

  1. Mysql Communication link failure :1153 Got a packet bigger than 'max_allowed_packet' bytes

    出现这种情况: 临时解决方法是: 登录mysql: 执行: set global max_allowed_packet=1000000000;       set global net_buffer_ ...

  2. Reflector.exe 破解注意事项

    需要把网络断掉,然后选择手动激活 总结经验:操作步骤要仔细看清,否则会更浪费时间

  3. Socket粘包问题

    这两天看csdn有一些关于socket粘包,socket缓冲区设置的问题,发现自己不是很清楚,所以查资料了解记录一下: 一两个简单概念长连接与短连接:1.长连接 Client方与Server方先建立通 ...

  4. XSS的原理分析与解剖(转)

    (转)http://netsecurity.51cto.com/art/201408/448305_all.htm 0×01 前言: <xss攻击手法>一开始在互联网上资料并不多(都是现成 ...

  5. iOS开发中打电话发短信等功能的实现

    在APP开发中,可能会涉及到打电话.发短信.发邮件等功能.比如说,通常一个产品的"关于"页面,会有开发者的联系方式,理想情况下,当用户点击该电话号码时,能够自动的帮用户拨出去,就涉 ...

  6. centos从日志文件查找关键字的日志并生成文件

    grep "unset user wechat user_id:" app* | tee wechat_log

  7. JavaWeb技术(三):JDBC中核心接口

    一.  DriverManager 接口 DriverManager 数据库连接驱动接口,用于获取数据库连接对象Connection import java.sql.Connection; impor ...

  8. C/C++中extern关键字解析

    1 基本解释:extern可以置于变量或者函数前,以标示变量或者函数的定义在别的文件中,提示编译器遇到此变量和函数时在其他模块中寻找其定义.此外extern也可用来进行链接指定. 也就是说extern ...

  9. mysql中left join ,right join 以及inner join 比较

    下面是例子分析表A记录如下: aID        aNum 1           a20050111 2           a20050112 3           a20050113 4   ...

  10. AdminLTE-2.2.0 学习

    这货基于Bootstrap 3(提供了统一的样式,覆盖了默认的),所以官方建议先搞懂Bootstrap 3再说. # 布局 Layout 布局由四个主要部分组成: Wrapper (.wrapper) ...