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