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文件代码如下
#!/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(" (.+)
| ")
weather = patternweather.findall(html)
patterntemperature = re.compile("([-]?\d{1,2}.+) | ")
temperature = patterntemperature.findall(html)
return weather[0]
def getWeather(url):
retval = htmlParser(getHtml(url))
return retval
阅读(701) | 评论(0) | 转发(0) |