Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1155480
  • 博文数量: 241
  • 博客积分: 4385
  • 博客等级: 上校
  • 技术积分: 2383
  • 用 户 组: 普通用户
  • 注册时间: 2009-06-07 23:13
文章分类

全部博文(241)

文章存档

2013年(1)

2012年(8)

2011年(62)

2010年(109)

2009年(61)

分类: Python/Ruby

2010-12-27 11:48:52

c语言调用python网上有很多范例,但是我在运行过程中发现找不到.py文件,后来试探着将.py文件中的class类去掉,只留下import module和def func语句,居然就能找到了!不行可以试下哈~~~
 
 
编译使用如下命令
 

gcc call_py.c -o getweather -I/usr/include/python2.5 -L/usr/lib/python2.5 -lpython2.5

.c文件代码如下

#include <stdio.h>
#include "/usr/include/python2.5/Python.h"

char *url = "";

int main()
{
    PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pRetVal;

    Py_Initialize();
    if(!Py_IsInitialized())
    {
        printf("Initialize failed!\n");
        return -1;
    }
    PyRun_SimpleString("print 'Initialize successed!'");
    
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");
    
    pName = PyString_FromString("getweather");
    pModule = PyImport_Import(pName);
    if(!pModule)
    {
        printf("Can't find getweather.py!\n");
        return -1;
    }
    PyRun_SimpleString("print 'Import web_1.py successed!'");
    
    pDict = PyModule_GetDict(pModule);
    if(!pDict )
    {
        return -1;
    }
    
    pFunc = PyDict_GetItemString(pDict, "getWeather");
    if(!pFunc || !PyCallable_Check(pFunc) )
    {
        printf("can't find function [getWeather]");
        return -1;
    }
    
    pArgs = PyTuple_New(1);
    PyTuple_SetItem(pArgs, 0, Py_BuildValue("s", url));
    pRetVal = PyObject_CallObject(pFunc, pArgs);
    printf("function return value : %s\n", PyString_AsString(pRetVal));
    
    Py_DECREF(pRetVal);
    Py_DECREF(pArgs);
    Py_DECREF(pFunc);
    Py_DECREF(pDict);
    Py_DECREF(pModule);
    Py_DECREF(pName);
    
    Py_Finalize();
    
    return 0;
}

.py文件代码如下

")
    weather = patternweather.findall(html)
    
    patterntemperature = re.compile("")
    temperature = patterntemperature.findall(html)

    return weather[0]

def getWeather(url):
    retval = htmlParser(getHtml(url))
    return retval

#!/usr/bin/env python
# -*- coding:utf8 -*-

import urllib2
import re
    
def getHtml(url):
    req = urllib2.Request(url)
    res = urllib2.urlopen(req)
    html = res.read().decode("gb2312").encode("utf8")
    res.close()
    
    return html
    
def htmlParser(html):
    patterndate = re.compile(">(\d{4}-\d{2}-\d{2} .+)<")
    date = patterndate.findall(html)
    
    patternweather = re.compile("
(.+)

([-]?\d{1,2}.+)

阅读(1622) | 评论(1) | 转发(1) |
给主人留下些什么吧!~~

chinaunix网友2010-12-30 12:38:24

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com