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_SimpleString
is 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 ab
C 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

Pythoncanbeoptimizedformemory-boundoperationsbyreducingoverheadthroughgenerators,efficientdatastructures,andmanagingobjectlifetimes.First,usegeneratorsinsteadofliststoprocesslargedatasetsoneitematatime,avoidingloadingeverythingintomemory.Second,choos

Install pyodbc: Use the pipinstallpyodbc command to install the library; 2. Connect SQLServer: Use the connection string containing DRIVER, SERVER, DATABASE, UID/PWD or Trusted_Connection through the pyodbc.connect() method, and support SQL authentication or Windows authentication respectively; 3. Check the installed driver: Run pyodbc.drivers() and filter the driver name containing 'SQLServer' to ensure that the correct driver name is used such as 'ODBCDriver17 for SQLServer'; 4. Key parameters of the connection string

Introduction to Statistical Arbitrage Statistical Arbitrage is a trading method that captures price mismatch in the financial market based on mathematical models. Its core philosophy stems from mean regression, that is, asset prices may deviate from long-term trends in the short term, but will eventually return to their historical average. Traders use statistical methods to analyze the correlation between assets and look for portfolios that usually change synchronously. When the price relationship of these assets is abnormally deviated, arbitrage opportunities arise. In the cryptocurrency market, statistical arbitrage is particularly prevalent, mainly due to the inefficiency and drastic fluctuations of the market itself. Unlike traditional financial markets, cryptocurrencies operate around the clock and their prices are highly susceptible to breaking news, social media sentiment and technology upgrades. This constant price fluctuation frequently creates pricing bias and provides arbitrageurs with

C folderexpressions is a feature introduced by C 17 to simplify recursive operations in variadic parameter templates. 1. Left fold (args...) sum from left to right, such as sum(1,2,3,4,5) returns 15; 2. Logical and (args&&...) determine whether all parameters are true, and empty packets return true; 3. Use (std::cout

Use psycopg2.pool.SimpleConnectionPool to effectively manage database connections and avoid the performance overhead caused by frequent connection creation and destruction. 1. When creating a connection pool, specify the minimum and maximum number of connections and database connection parameters to ensure that the connection pool is initialized successfully; 2. Get the connection through getconn(), and use putconn() to return the connection to the pool after executing the database operation. Constantly call conn.close() is prohibited; 3. SimpleConnectionPool is thread-safe and is suitable for multi-threaded environments; 4. It is recommended to implement a context manager in combination with context manager to ensure that the connection can be returned correctly when exceptions are noted;

ABinarySearchTree(BST)isabinarytreewheretheleftsubtreecontainsonlynodeswithvalueslessthanthenode’svalue,therightsubtreecontainsonlynodeswithvaluesgreaterthanthenode’svalue,andbothsubtreesmustalsobeBSTs;1.TheC implementationincludesaTreeNodestructure

References are alias for variables, which must be initialized at declaration and cannot be rebinded. 1. References share the same memory address through alias. Modifying any name will affect the original value; 2. References can be used to achieve bidirectional transmission and avoid copy overhead; 3. References cannot be empty and have the grammar, and do not have the ability to repoint compared to pointers; 4. ConstT& can be used to safely pass parameters, prevent modification and support binding of temporary objects; 5. References of local variables should not be returned to avoid dangling reference errors. Mastering citations is the key foundation for understanding modern C.

Use fromrichimportprint to output color, bold, and italic text, such as [boldred] error: [/boldred] file does not exist; 2. Print dictionary directly or use pprint to automatically beautify the JSON data structure and highlight the syntax; 3. Create a table with color and alignment through the Table class, suitable for displaying structured information; 4. Use the track function to quickly implement progress bars with progress percentage and remaining time; 5. Integrate RichHandler to logging to beautify log output and highlight the exception stack; 6. Use the Syntax class to highlight code blocks with line numbers in the terminal; 7. Use the Markdown class to parse and beautiful
