Python和C扩展实现方法
一、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扩展实现方法的更多相关文章
- python获取文件扩展名的方法(转)
主要介绍了python获取文件扩展名的方法,涉及Python针对文件路径的相关操作技巧.具体实现方法如下: 1 2 3 4 import os.path def file_extension(path ...
- python获取文件扩展名的方法
主要介绍了python获取文件扩展名的方法,涉及Python针对文件路径的相关操作技巧 import os.path def file_extension(path): ] print file_ex ...
- sqlalchemy mark-deleted 和 python 多继承下的方法解析顺序 MRO
sqlalchemy mark-deleted 和 python 多继承下的方法解析顺序 MRO 今天在弄一个 sqlalchemy 的数据库基类的时候,遇到了跟多继承相关的一个小问题,因此顺便看了一 ...
- python类:magic魔术方法
http://blog.csdn.net/pipisorry/article/details/50708812 魔术方法是面向对象Python语言中的一切.它们是你可以自定义并添加"魔法&q ...
- (转)python类:magic魔术方法
原文:https://blog.csdn.net/pipisorry/article/details/50708812 版权声明:本文为博主皮皮http://blog.csdn.net/pipisor ...
- python使用C扩展
CPython还为开发者实现了一个有趣的特性,使用Python可以轻松调用C代码 开发者有三种方法可以在自己的Python代码中来调用C编写的函数-ctypes,SWIG,Python/C API.每 ...
- openresty 学习笔记番外篇:python的一些扩展库
openresty 学习笔记番外篇:python的一些扩展库 要写一个可以使用的python程序还需要比如日志输出,读取配置文件,作为守护进程运行等 读取配置文件 使用自带的ConfigParser模 ...
- 使用pybind11为Python编写C++扩展(一)配置篇:Build(编译和链接)
目录 Setuptools CMake 最后决定选用pybind11,理由如下: 比python原生的C API看起来人性多了 我的C++代码不是现成的,需要一定的C++开发工作量,所以感觉cytho ...
- jquery 扩展插件方法
分析插件jquery.countdown.js (function($) { $.fn.countdown = function(options) { // default options var d ...
随机推荐
- 三款Javascript SPAs框架资料整理和总结
一.框架介绍 RequireJS 资料:http://www.requirejs.cn/RequireJS的目标是鼓励代码的模块化,它使用了不同于传统<script>标签的脚本加载步骤.可 ...
- malloc 函数工作机制(转)
malloc()工作机制 malloc函数的实质体现在,它有一个将可用的内存块连接为一个长长的列表的所谓空闲链表.调用malloc函数时,它沿连接表寻找一个大到足以满足用户请求所需要的内存块.然后,将 ...
- Appium移动自动化测试之Eclipse
下载eclipse,这个下载方式比较多,eclipse官网,CSDN都有的下,版本根据自己操作系统选择,切记eclipse版本一定要与JDK版本一至,不然eclipse无法启动.现在我们来搭建Andr ...
- linux提取指定字符的行列并生成新文件(awk命令)
如图所示,命名为file文件的表头有BP.A1.TEST等 假如想提取含有"ADD"的行和该行对应列的"BP"和"P"值,则需要用到以下命令 ...
- linux下python调用c模块
在C调用Python模块时需要初始化Python解释器,导入模块等,但Python调用C模块却比较简单,下面还是以helloWorld.c 和 main.py 做一说明: (1)编写C代码,hel ...
- 课堂Beta发布140字评论
Beta发布140字评论: 第一组:飞天小女警 此项目组的功能是礼物挑选,创意十足,用户只要一听名字便会被深深吸引,并且页面设计感,时尚感十足,不断吸引客户的眼球,而且发布到云服务器上面. 第二组:金 ...
- 更新CocoaPods
终端输入 : sudo gem install -n /usr/local/bin cocoapods –pre 更新了CocoaPods后,在原来的工程中执行了pod install命令后,报这样的 ...
- 读取xml文件报错:Invalid byte 2 of 2-byte UTF-8 sequence。
程序读取xml文件后,系统报“Invalid byte 2 of 2-byte UTF-8 sequence”错误,如何解决呢? 1.程序解析xml的时候,出现Invalid byte 2 of 2- ...
- controller错误统一处理--------@ExceptionHandler
用@RequestBody,@ResponseBody,不费吹灰之力就解决了JSon自动绑定.接着就发现,如果遇到RuntimeException,需要给出一个默认返回JSON 三种方式: 1.当这个 ...
- Sql Server 分区之后增加新的分区
随着时间的推移,你可能会希望为已分区的表添加额外的分区(例如,可以为每一个新年创建一个新的分区).要增加一个新的分区,可以使用ALTER PARTITION SCHEME和ALTER PARTITIO ...