Python simple tips and common references
Python file supports 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)
Gets the path to the current Python script file
Import OS
Os.path.split (Os.path.realpath (__file__)) [0]
Problems with the import of JSON modules
Try:
Import JSON
Except:
Import Simplejson as JSON
Format JSON with the JSON tool
#python 2.7 or less
Echo\ ' {\ ' hello\ ': 1}\ ' | Python-m Simplejson.tool
#python 2.7 and above
Echo\ ' {\ ' hello\ ': 1}\ ' | Python-m Json.tool
General invocation Steps
Py_initialize (); Initializing the Python environment
Pyimport_importmodule ("test"); Loading the Python module
Pyobject_getattrstring (G_pmodule, "test1"); Get the pyobject of the corresponding Python function
Pyobject_callfunction (test1, "I,s", 2,e); Invoke Python's corresponding function
Py_finalize (); End
Sample code for C language
#include
int main () {
Pyobject * G_pmodule = NULL;
Py_initialize (); To call Py_initialize () before using Python, 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");//Here is the name of the file to invoke, we are here under the current directory test.py
if (!g_pmodule) {
printf ("Cant open Python file!\n");
Return-2;
}
Pyobject * test1 = pyobject_getattrstring (G_pmodule, "test1");//This is the name of the function to invoke
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");//This is the name of the function to invoke
Objresult = Pyobject_callfunction (test2, "I", 2);//Call function
char * x = pystring_asstring (Objresult);
printf ("%s\n", X);
Py_finalize ();//Call Py_finalize, this corresponds to Py_initialize.
}
Python program mytest.py
def test1 (S,STR):
Print S+str
return 0
def test2 (s):
return s
Compiling method of C program
#假设我们的python编译的时候安装在/opt/python, then we can use this command to compile the program.
$GCC-i/opt/python/include-l/opt/python/lib/-lpython2.7 test.c
Note: When Python is compiled, a dynamic link library is required to add--enable-shared
./configure--prefix=/opt/python--enable-shared
http://www.bkjia.com/PHPjc/895550.html www.bkjia.com true http://www.bkjia.com/PHPjc/895550.html techarticle python simple tips and common reference python files support Chinese #-*-coding:utf-8-*-Execute shell command from subprocess import Popen, PIPE def run_cmd (cmd): #P Open Call Wrapper.return ...