Example of C program calling Python script

Source: Internet
Author: User
The code is as follows: Copy code

# 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 errorn ");
Return-1;
}
PyRun_SimpleString ("import sys ");
PyRun_SimpleString ("sys. path. append ('./')");
G_pModule = PyImport_ImportModule ("test"); // 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 failn ");
}
 
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 ("% sn", x );
Py_Finalize (); // call Py_Finalize, which corresponds to Py_Initialize.
}

Python program test. py

The code is as follows: Copy code

Def test1 (s, str ):
Print s + str
Return 0
Def test2 (s ):
Return s

C program compilation method

The code is as follows: Copy code

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

The code is as follows: Copy code

./Configure -- prefix =/opt/python -- enable-shared

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.