Home > php教程 > php手册 > Python简单技巧和常用参考

Python简单技巧和常用参考

WBOY
Release: 2016-06-13 09:23:42
Original
857 people have browsed it

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 
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

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template