Python simple tips and common references
Python files support Chinese Characters
#-*-Coding: UTF-8 -*-
Execute shell commands
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)
Obtain the path of the current python script file
Import OS
OS. path. split (OS. path. realpath (_ file _) [0]
Json module import problems
Try:
Import json
Except t:
Import simplejson as json
Use the json tool to format json
# Python 2.7 or lower
Echo \ '{\ "hello \": 1} \' | python-m simplejson. tool
# Python 2.7 and later
Echo \ '{\ "hello \": 1} \' | python-m json. tool
General call steps
Py_Initialize (); // initialize the Python Environment
PyImport_ImportModule ("test"); // load the python Module
PyObject_GetAttrString (g_pModule, "test1"); // obtain the PyObject of the corresponding Python Function
PyObject_CallFunction (test1, "I, s", 2, e); // call the corresponding Python Function
Py_Finalize (); // end
Sample Code in C Language
# Include <python2.7/Python. h>
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"); // The name of the file to be called. Here we are test. py in the current directory.
If (! G_pModule ){
Printf ("Cant open python file! \ N ");
Return-2;
}
PyObject * test1 = PyObject_GetAttrString (g_pModule, "test1"); // The Name Of The function to be called.
PyObject * objResult = PyObject_CallFunction (test1, "I, s", 2, e); // call a function
If (! ObjResult ){
Printf ("invoke function fail \ n ");
}
PyObject * test2 = PyObject_GetAttrString (g_pModule, "test2"); // The Name Of The function to be called.
ObjResult = PyObject_CallFunction (test2, "I", 2); // call a 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
C program Compilation Method
# If we install python in/opt/python during compilation, we can use this command to compile the program.
$ Gcc-I/opt/python/include-L/opt/python/lib/-lpython2.7 test. c
Note: To compile python, you must add the -- enable-shared library to the dynamic link library.
./Configure -- prefix =/opt/python -- enable-shared