Home >Backend Development >PHP Tutorial >Python simple skills and common references_PHP tutorial
python files support Chinese
# -*- coding: UTF-8 -*-
Execute shell command
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)
Get the path of the current python script file
import os
os.path.split(os.path.realpath(__file__))[0]
Problems with json module import
try :
Import json
except :
Import simplejson as json
Use json tool to format json
#python 2.7 or below
echo \'{\"hello\":1}\' | python -m simplejson.tool
#python 2.7 and above
echo \'{\"hello\":1}\' | python -m json.tool
General calling steps
Py_Initialize(); //Initialize the Python environment
PyImport_ImportModule("test"); // Load python module
PyObject_GetAttrString(g_pModule,"test1"); //Get the PyObject
of the corresponding Python function
PyObject_CallFunction(test1,"i,s",2,e); //Call the corresponding function in Python
Py_Finalize(); //End
Sample code in C language
#include
int main(){
PyObject * g_pModule = NULL;
Py_Initialize(); //Before using python, you need to call Py_Initialize(); this function is initialized
If (!Py_IsInitialized())
{
printf("init error\n");
return -1;
}
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
g_pModule =PyImport_ImportModule("mytest");//This is the file name to be called, here is test.py
in the current directory
If (!g_pModule) {
printf("Cant open python file!\n");
Return -2;
}
PyObject * test1 = PyObject_GetAttrString(g_pModule,"test1"); //Here is the function name to be called
PyObject *objResult = PyObject_CallFunction(test1,"i,s",2,e);//Call function
if (!objResult){
printf("invoke function fail\n");
}
PyObject * test2= PyObject_GetAttrString(g_pModule,"test2"); //Here is the function name to be called
objResult = PyObject_CallFunction(test2,"i",2);//Call function
char * x = PyString_AsString(objResult);
printf("%s\n",x);
Py_Finalize();//Call Py_Finalize, which corresponds to Py_Initialize.
}
Python program mytest.py
def test1(s,str):
Print s+str
Return 0
def test2(s):
Return s
Compilation method of C program
# Assuming that our python is installed in /opt/python when compiling, then we can use such a command to compile the program
$gcc -I/opt/python/include -L/opt/python/lib/ -lpython2.7 test.c
Note: When compiling python, you need to have a dynamic link library and add --enable-shared
./configure --prefix=/opt/python --enable-shared