Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6319891
  • 博文数量: 2759
  • 博客积分: 1021
  • 博客等级: 中士
  • 技术积分: 4091
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-11 14:14
文章分类

全部博文(2759)

文章存档

2019年(1)

2017年(84)

2016年(196)

2015年(204)

2014年(636)

2013年(1176)

2012年(463)

分类:

2012-05-07 23:46:45

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}.+)

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