tables.py
global gtables
gtables = {
1001:"张鲁p",
1002:"凌p",
2001:"李进a",
2002:"vb"
}
from tables import gtables
def get_cmd(key, value): name ="0"; try: name = gtables[key] except KeyError: return 0,name name = name + "=" + str(value) type = 1000 if (2000 <= key and key <3999): type = 2000 elif (4000 <= key and key< 5999): type = 4000 elif (6000 <= key and key <7999): type = 6000 elif (8000 <= key and key <9999): type = 8000 return type, name
def run(): x, result = get_cmd(1,"test") print(0, result) if __name__=="__main__": run()
gcc -o test script_py.c -I/usr/include/python2.6 -lpython2.6 -L/usr/lib/python2.6/config
注意:库的位置
c代码,注意头文件Python.h P为大些
#include <Python.h>
/* module:
Python脚步的模块名
function: 要调用的函数名
format: 传递给Py_VaBuildValue函数的可变参数模板
*/
char* PyCall( const char * module, const char * function, const char *format, ... )
{
PyObject* pMod = NULL;
PyObject* pFunc = NULL;
PyObject* pParm = NULL;
PyObject* pRetVal = NULL;
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
//导入模块
if( !(pMod = PyImport_ImportModule(module) ) )
{
return 0;
}
//查找函数
if( !(pFunc = PyObject_GetAttrString(pMod, function) ) )
{
return 0;
}
//创建参数
va_list vargs;
va_start( vargs, format );
pParm = Py_VaBuildValue( format, vargs ); va_end(vargs);
//函数调用 pRetVal = PyEval_CallObject( pFunc, pParm);
int type; char* ret;
int len;
PyArg_Parse( pRetVal, "(is#)", &type, &ret, &len);
char* pret = (char*)malloc(len+1);
memset(pret, 0, len+1); strcpy(pret, ret);
Py_DECREF(pRetVal);
Py_DECREF(pParm);
Py_DECREF(pFunc);
Py_DECREF(pMod);
return pret;
}
int main(int argc, char* argv[])
{
Py_Initialize();
/* 这做个简单的说明 ** format参数用()扩起来是表示元组的意思。元组中的个数对应Python脚本中的参数。 ** 因为fun,fun1,fun2函数的参数个数分别是 0,1,2,所以,元组中的个数必须为0,1,2,不然调用将失 ** 败。当然,元组中的每个元素都是可以为任意的类型,比如: ** PyCall( "pytest", "fun2", "( i,{s:s,s:s})", 2, "name", "linxr", "age", "25" ); */
char* p = PyCall( "script_main", "get_cmd", "(is)",1001,"test");
if(0 != p)
printf("%s\n", p);
Py_Finalize(); return 0; }
参考http://www.cnblogs.com/linxr/archive/2011/07/22/2113843.html 稍作修改,支持路径加载和返回多个值