How to call Python from C ?
To call Python code in C, you must first initialize the interpreter, and then you can achieve interaction by executing strings, files, or calling specific functions. 1. Use Py_Initialize() to initialize the interpreter and close it with Py_Finalize(); 2. Use PyRun_SimpleString to execute string code or PyRun_SimpleFile to execute script files; 3. Import the module through PyImport_ImportModule, get the function through PyObject_GetAttrString, construct parameters of Py_BuildValue, call the function through PyObject_CallObject and process the return value; 4. Pay attention to version matching, path setting, reference count management and exception check. The entire process is structured clearly but requires careful handling of errors and resource management.

Calling Python code from C programs is not actually mysterious. The key is to use the C API provided by Python. As long as it is configured properly, you can create interpreters, execute scripts, and even pass parameters in C.

Initialize the Python interpreter
To call Python in C, the first step is to initialize the Python interpreter. This step is necessary, otherwise subsequent operations will fail.

- Use
Py_Initialize()to start the interpreter - Remember to call
Py_Finalize()after use to free the resource - If your program may be initialized and closed multiple times, you need to pay attention to thread safety issues (Python does not support multi-threaded embedding by default)
Sample code snippet:
#include <Python.h>
int main() {
Py_Initialize();
// ... The code that calls Python Py_Finalize();
return 0;
} Note: You need to link Python libraries when compiling, such as using the -lpython3.10 parameter (the specific version depends on the Python version you installed).

Execute a simple Python script or statement
Once initialization is complete, you can directly run a piece of Python string code, such as printing a sentence or defining a function.
- Using
PyRun_SimpleStringis the easiest way - It is suitable for executing some statements that do not require a return value
For example:
PyRun_SimpleString("print('Hello from Python!')"); If you want to go a step further, such as executing a .py file, you can do this:
FILE* fp = fopen("script.py", "r");
if (fp) {
PyRun_SimpleFile(fp, "script.py");
fclose(fp);
}This method is suitable for situations when you want to load the entire script file, but be careful whether the path is correct and whether the file is readable.
Call Python function and get the return value
If you want to call a specific Python function and get its return value, you need a slightly more complicated operation.
The steps are as follows:
- Import module: Use
PyImport_ImportModule - Get function object: Use
PyObject_GetAttrString - Construct parameters: Create tuple or other types using
Py_BuildValue - Call function: Use
PyObject_CallObject - Process the return value: Check whether it is NULL, and then extract the actual value
For example, suppose there is a file called math_utils.py , with a function called add :
# math_utils.py
def add(a, b):
return abC calls it as follows:
PyObject* pModule = PyImport_ImportModule("math_utils");
PyObject* pFunc = PyObject_GetAttrString(pModule, "add");
PyObject* pArgs = PyTuple_Pack(2, PyLong_FromLong(3), PyLong_FromLong(4));
PyObject* pResult = PyObject_CallObject(pFunc, pArgs);
long result = PyLong_AsLong(pResult);
// result == 7 This process is quite cumbersome, but the structure is clear. The key is to handle error checks at each step, such as determining whether pModule is NULL to avoid crashes.
Frequently Asked Questions and Precautions
- Python version matching : Make sure your C compile environment is linked to the correct Python version, otherwise compatibility issues may occur.
- Path settings : If the Python script is not in the current directory, you may need to set the search path through
PySys_SetPath. - Reference Count Management : Python uses the reference counting mechanism, remember to increase or decrease references appropriately to avoid memory leaks.
- Exception handling : It is best to check whether any exceptions occur after each call to the Python API. You can use
PyErr_Occurred()to judge.
Basically that's it. Although it seems a bit troublesome, as long as you follow the process step by step, you can successfully implement the function of C calling Python.
The above is the detailed content of How to call Python from C ?. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
Accessing data from a web API in Python
Jul 16, 2025 am 04:52 AM
The key to using Python to call WebAPI to obtain data is to master the basic processes and common tools. 1. Using requests to initiate HTTP requests is the most direct way. Use the get method to obtain the response and use json() to parse the data; 2. For APIs that need authentication, you can add tokens or keys through headers; 3. You need to check the response status code, it is recommended to use response.raise_for_status() to automatically handle exceptions; 4. Facing the paging interface, you can request different pages in turn and add delays to avoid frequency limitations; 5. When processing the returned JSON data, you need to extract information according to the structure, and complex data can be converted to Data
Understanding move assignment operator in C
Jul 16, 2025 am 02:20 AM
ThemoveassignmentoperatorinC isaspecialmemberfunctionthatefficientlytransfersresourcesfromatemporaryobjecttoanexistingone.ItisdefinedasMyClass&operator=(MyClass&&other)noexcept;,takinganon-constrvaluereferencetoallowmodificationofthesour
Object Slicing in C
Jul 17, 2025 am 02:19 AM
Object slice refers to the phenomenon that only part of the base class data is copied when assigning or passing a derived class object to a base class object, resulting in the loss of new members of the derived class. 1. Object slices occur in containers that directly assign values, pass parameters by value, or store polymorphic objects in storage base classes; 2. The consequences include data loss, abnormal behavior and difficult to debug; 3. Avoiding methods include passing polymorphic objects using pointers or references, or using smart pointers to manage the object life cycle.
How to update a JSON file in Python?
Jul 16, 2025 am 03:49 AM
Updating a JSON file requires three steps: reading, modifying, and writing. 1. Use json.load() to read the file into a Python data structure; 2. Access the modified value through keys such as data['age']=31 or nested modification; 3. Use json.dump(data,f) to save the changes back to the file and it is recommended to add indent to beautify the output. Before operation, you should confirm that the file exists and backups should be made if necessary. Remote data must be processed in conjunction with the requests module.
Running code in parallel with Python multiprocessing
Jul 16, 2025 am 03:51 AM
Using Python's multiprocessing module can improve performance, but attention should be paid to startup methods, Pool usage, process communication and exception handling. 1. Choose the appropriate startup method: fork (Unix fast but unstable), spawn (cross-platform recommendation), forkserver (property-suitable for frequent creation); 2. Use Pool to manage concurrent tasks, control the number of processes, and reasonably select map or apply_async; 3. Inter-process communication can be used to provide Queue, Pipe, Value, Array or Manager, pay attention to performance and security; 4. Strengthen exception handling, use logging to debug, and can be simulated by a single process during development.
What are magic methods (dunder methods) in Python?
Jul 16, 2025 am 04:09 AM
Magic methods (dunder methods) in Python are special methods used to customize object behavior. They start and end with a double underscore, such as __init__ or __str__, and are automatically triggered when a specific syntax or built-in function is used. 1.__init__ is used to initialize the object; 2.__str__ and __repr__ define the readable string representation and reconstructible expression of the object respectively; 3.__add__, __sub__, etc. define the addition and subtraction operation behaviors; 4. Control and comparison operations such as __eq__, __lt__, etc. Implementing these methods, such as adding __add__ to custom class Point to support operations, makes the class behave more naturally and in line with expectations. make
C Initialization techniques
Jul 18, 2025 am 04:13 AM
There are many initialization methods in C, which are suitable for different scenarios. 1. Basic variable initialization includes assignment initialization (inta=5;), construction initialization (inta(5);) and list initialization (inta{5};), where list initialization is more stringent and recommended; 2. Class member initialization can be assigned through constructor body or member initialization list (MyClass(intval):x(val){}), which is more efficient and suitable for const and reference members. C 11 also supports direct initialization within the class; 3. Array and container initialization can be used in traditional mode or C 11's std::array and std::vector, support list initialization and improve security; 4. Default initialization
Random Number Generation in C
Jul 16, 2025 am 02:27 AM
There are two main ways to generate random numbers in C. 1. The rand() function in use needs to be used to set the seed with srand(), but the randomness is poor; 2. It is recommended to use the C 11 library to achieve higher quality random number generation through random_device, mt19937 engine and distribution objects. Be careful to avoid repeated seed setting, avoid direct molding control range, and prioritize modern libraries to ensure cross-platform consistency and random quality.


