1、c程序中内嵌python
Wednesday, April 12, 2006 1:39:56 PM
对这个程序的基本构想是使用c和python混合的插件方式
网上以及本地的资源?(应该是这样解释吧;D)。
我不知道这个程序能写到怎样的程度,就全当是练习吧!
反正正好觉得那个gdict没什么出路正好改成它的插件。
这几天正好在实验c内嵌python所以有些东西还是整理一下,免得以后忘记!
好了,开始正题吧,费话不多说直接举例子:
[yurt@yurt ~/pythontmp]
<2 files 17K>
>>>cat pythc1.c
#include <Python.h>
int main()
{
Py_Initialize(); // 初始化python
PyRun_SimpleString("print 'Hello Python'"); // 执行一条简单的语句相当于python中的 print 'Hello Python'
Py_Finalize(); // 结束
return 0;
}
[yurt@yurt ~/pythontmp]
<2 files 17K>
>>>gcc pythc1.c -o pythc1 -lpython2.4 -I/usr/include/python2.4
[yurt@yurt ~/pythontmp]
<2 files 17K>
>>>./pythc1
Hello Python
接下来请看这个程序
[yurt@yurt ~/pythontmp]
<2 files 17K>
>>>cat test.py
import urllib
page = urllib.urlopen( 'http://www.google.com' )
content = page.read()
print content
让我们来用内嵌的方法解决同样的问题:
[yurt@yurt ~/pythontmp]
<2 files 17K>
>>>cat pythc2.c
#include <Python.h>
int main()
{
Py_Initialize();
PyRun_SimpleString("import urllib \n" );
PyRun_SimpleString( "page = urllib.urlopen('http://www.google.com')\n" );
PyRun_SimpleString( "content = page.read()\n" );
PyRun_SimpleString( "print content\n" );
Py_Finalize();
return 0;
}
其实这个语句可以放在一条里的
PyRun_SimpleString(
"import urllib \n"
"page = urllib.urlopen('http://www.google.com')\n"
"content = page.read()\n"
"print content\n" );
[yurt@yurt ~] [21:41:53 ]
<2 files 50M >
>>>\






