标题 | python简单技巧和常用参考 |
内容 | python文件支持中文 # -*- coding: utf-8 -*- 执行shell命令 from subprocess import popen, pipe def run_cmd(cmd): #popen call wrapper.return (code, stdout, stderr) child = popen(cmd, stdin = pipe, stdout = pipe, stderr = pipe, shell = true) out, err = child.communicate() ret = child.wait() return (ret, out, err) 获取当前python脚本文件所在路径 import os os.path.split(os.path.realpath(__file__))[0] json模块 import的问题 try : import json except : import simplejson as json 使用json工具格式化json #python 2.7以下 echo \'{\hello\:1}\' | python -m simplejson.tool #python 2.7及以上 echo \'{\hello\:1}\' | python -m json.tool 一般调用步骤 py_initialize(); //初始化python环境 pyimport_importmodule(test); // 载入python模块 pyobject_getattrstring(g_pmodule,test1); //获得相应python函数的pyobject pyobject_callfunction(test1,i,s,2,e); //调用python相应的函数 py_finalize(); //结束 c语言的示例代码 #include <python2.7/python.h> int main(){ pyobject * g_pmodule = null; py_initialize(); //使用python之前,要调用py_initialize();这个函数进行初始化 if (!py_isinitialized()) { printf(init error\n); return -1; } pyrun_simplestring(import sys); pyrun_simplestring(sys.path.append('./')); g_pmodule =pyimport_importmodule(mytest);//这里是要调用的文件名,我们这里是当前目录下test.py if (!g_pmodule) { printf(cant open python file!\n); return -2; } pyobject * test1 = pyobject_getattrstring(g_pmodule,test1);//这里是要调用的函数名 pyobject *objresult = pyobject_callfunction(test1,i,s,2,e);//调用函数 if (!objresult){ printf(invoke function fail\n); } pyobject * test2= pyobject_getattrstring(g_pmodule,test2);//这里是要调用的函数名 objresult = pyobject_callfunction(test2,i,2);//调用函数 char * x = pystring_asstring(objresult); printf(%s\n,x); py_finalize();//调用py_finalize,这个跟py_initialize相对应的。 } python程序mytest.py def test1(s,str): print s+str return 0 def test2(s): return s c程序的编译方法 #假设我们的python编译的时候安装在/opt/python里,那么我们可以用这样的命令来编译程序 $gcc -i/opt/python/include -l/opt/python/lib/ -lpython2.7 test.c 注意: 这里要求python编译的时候,需要有动态链接库即加上--enable-shared ./configure --prefix=/opt/python --enable-shared |
随便看 |
|
在线学习网考试资料包含高考、自考、专升本考试、人事考试、公务员考试、大学生村官考试、特岗教师招聘考试、事业单位招聘考试、企业人才招聘、银行招聘、教师招聘、农村信用社招聘、各类资格证书考试等各类考试资料。