python簡單技巧和常用參考

字號(hào):


    python文件支持中文
    # -*- coding: utf-8 -*-
    執(zhí)行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)
    獲取當(dāng)前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
    一般調(diào)用步驟
    py_initialize(); //初始化python環(huán)境
    pyimport_importmodule(test); // 載入python模塊
    pyobject_getattrstring(g_pmodule,test1); //獲得相應(yīng)python函數(shù)的pyobject
    pyobject_callfunction(test1,i,s,2,e); //調(diào)用python相應(yīng)的函數(shù)
    py_finalize(); //結(jié)束
    c語言的示例代碼
    #include <python2.7/python.h>
    int main(){
    pyobject * g_pmodule = null;
    py_initialize(); //使用python之前,要調(diào)用py_initialize();這個(gè)函數(shù)進(jìn)行初始化
    if (!py_isinitialized())
    {
    printf(init error\n);
    return -1;
    }
    pyrun_simplestring(import sys);
    pyrun_simplestring(sys.path.append('./'));
    g_pmodule =pyimport_importmodule(mytest);//這里是要調(diào)用的文件名,我們這里是當(dāng)前目錄下test.py
    if (!g_pmodule) {
    printf(cant open python file!\n);
    return -2;
    }
    pyobject * test1 = pyobject_getattrstring(g_pmodule,test1);//這里是要調(diào)用的函數(shù)名
    pyobject *objresult = pyobject_callfunction(test1,i,s,2,e);//調(diào)用函數(shù)
    if (!objresult){
    printf(invoke function fail\n);
    }
    pyobject * test2= pyobject_getattrstring(g_pmodule,test2);//這里是要調(diào)用的函數(shù)名
    objresult = pyobject_callfunction(test2,i,2);//調(diào)用函數(shù)
    char * x = pystring_asstring(objresult);
    printf(%s\n,x);
    py_finalize();//調(diào)用py_finalize,這個(gè)跟py_initialize相對應(yīng)的。
    }
    python程序mytest.py
    def test1(s,str):
    print s+str
    return 0
    def test2(s):
    return s
    c程序的編譯方法
    #假設(shè)我們的python編譯的時(shí)候安裝在/opt/python里,那么我們可以用這樣的命令來編譯程序
    $gcc -i/opt/python/include -l/opt/python/lib/ -lpython2.7 test.c
    注意: 這里要求python編譯的時(shí)候,需要有動(dòng)態(tài)鏈接庫即加上--enable-shared
    ./configure --prefix=/opt/python --enable-shared