Calling Python scripts in C requires the implementation of Python C API. First, initialize the interpreter, then import the module and call the functions, and finally clean up the resources; the specific steps are: 1. Initialize the Python interpreter with Py_Initialize(); 2. Load the Python script module with PyImport_Import(); 3. Obtain the objective function through PyObject_GetAttrString(); 4. Use PyObject_CallObject() to pass parameters to call the function; 5. Calling Py_DECREF() and Py_Finalize() to release resources and close the interpreter; in the example, the greet and add functions of hello.py are successfully called and the results are output. The entire process needs to ensure that the Python development environment is configured correctly, the script path is accessible, and attention should be paid to the matching of memory management and version. The final program can run normally and output the expected results.
Calling Python scripts in C is a common requirement, especially when it is necessary to take advantage of Python's rich libraries (such as NumPy, Pandas, machine learning models, etc.). C can be directly embedded and executed through the Python C API . Here is a simple, runnable example showing how to call a Python script from C.

? Prerequisites
- Install Python development environment (including header files and libraries)
- Linking Python libraries at compile time (such as
libpython3.x
) - Use a compiler that supports C 11 and above
? Example structure
project/ ├── main.cpp // C main program ├── hello.py // Python script to be called
1. Write Python script: hello.py
# hello.py def greet(name): return f"Hello, {name} from Python!" def add(a, b): return ab # Directly executed code print("Python script is running...")
2. C program: main.cpp
#include <Python.h> #include <iostream> int main() { // Initialize the Python interpreter Py_Initialize(); if (!Py_IsInitialized()) { std::cerr << "Failed to initialize Python" << std::endl; return -1; } // Import Python script (assuming the file name is hello.py) PyObject* pName = PyUnicode_DecodeFSDefault("hello"); PyObject* pModule = PyImport_Import(pName); if (!pModule) { PyErr_Print(); std::cerr << "Failed to load module 'hello'" << std::endl; Py_Finalize(); return -1; } // Call greet(name) function { PyObject* pFunc = PyObject_GetAttrString(pModule, "greet"); if (pFunc && PyCallable_Check(pFunc)) { PyObject* pArgs = PyTuple_New(1); PyTuple_SetItem(pArgs, 0, PyUnicode_FromString("Alice")); PyObject* pResult = PyObject_CallObject(pFunc, pArgs); if (pResult) { const char* result = PyUnicode_AsUTF8(pResult); std::cout << "Result from Python: " << result << std::endl; Py_DECREF(pResult); } else { PyErr_Print(); } Py_DECREF(pArgs); Py_XDECREF(pFunc); } else { std::cerr << "Function 'greet' not found or not callable" << std::endl; } } // Call the add(a, b) function { PyObject* pFunc = PyObject_GetAttrString(pModule, "add"); if (pFunc && PyCallable_Check(pFunc)) { PyObject* pArgs = PyTuple_New(2); PyTuple_SetItem(pArgs, 0, PyLong_FromLong(10)); PyTuple_SetItem(pArgs, 1, PyLong_FromLong(20)); PyObject* pResult = PyObject_CallObject(pFunc, pArgs); if (pResult) { long result = PyLong_AsLong(pResult); std::cout << "add(10, 20) = " << result << std::endl; Py_DECREF(pResult); } else { PyErr_Print(); } Py_DECREF(pArgs); Py_XDECREF(pFunc); } else { std::cerr << "Function 'add' not found or not callable" << std::endl; } } // Clean Py_DECREF(pModule); Py_DECREF(pName); Py_Finalize(); return 0; }
3. Compile command (Linux/macOS)
Assuming using Python 3.8, first confirm your Python configuration:
python3-config --includes --libs
Then compile:

g main.cpp -o run \ $(python3-config --includes --libs) \ -lpython3.10 # Adjust according to your actual version
For example:
g main.cpp -o run `python3-config --includes --libs`
?? Note: On some systems it may be necessary to specify
-lpython3.x
explicitly, or usepkg-config python3 --cflags --libs
.
4. Operation results
./run
Output:
Python script is running... Results from Python: Hello, Alice from Python! add(10, 20) = 30
? FAQs and Suggestions
- Make sure
hello.py
is in the current working directory , otherwise Python cannot find the module. - Use
PyRun_SimpleString("exec(open('script.py').read())");
to execute the contents of the.py
file. - In multi-threaded environments, you need to pay attention to GIL (global interpreter lock).
- When publishing the program, you need to make sure that the target machine has the corresponding version of Python installed.
? Summary
- Start the Python interpreter with
Py_Initialize()
- Loading
.py
files withPyImport_Import
- Use
PyObject_GetAttrString
to get the function - Call the function with
PyObject_CallObject
and pass the parameters - Remember
Py_DECREF
to prevent memory leaks - Finally
Py_Finalize()
cleans up resources
Basically that's it. As long as the environment is configured correctly, this example can be run quickly. In actual projects, you can also encapsulate them into classes or tool functions to simplify calls.
The above is the detailed content of C call python script from C example. 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)

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

iter() is used to obtain the iterator object, and next() is used to obtain the next element; 1. Use iterator() to convert iterable objects such as lists into iterators; 2. Call next() to obtain elements one by one, and trigger StopIteration exception when the elements are exhausted; 3. Use next(iterator, default) to avoid exceptions; 4. Custom iterators need to implement the __iter__() and __next__() methods to control iteration logic; using default values is a common way to safe traversal, and the entire mechanism is concise and practical.

The recommended way to read files line by line in Python is to use withopen() and for loops. 1. Use withopen('example.txt','r',encoding='utf-8')asfile: to ensure safe closing of files; 2. Use forlineinfile: to realize line-by-line reading, memory-friendly; 3. Use line.strip() to remove line-by-line characters and whitespace characters; 4. Specify encoding='utf-8' to prevent encoding errors; other techniques include skipping blank lines, reading N lines before, getting line numbers and processing lines according to conditions, and always avoiding manual opening without closing. This method is complete and efficient, suitable for large file processing

TorunaPythonscriptwithargumentsinVSCode,configurelaunch.jsonbyopeningtheRunandDebugpanel,creatingoreditingthelaunch.jsonfile,andaddingthedesiredargumentsinthe"args"arraywithintheconfiguration.2.InyourPythonscript,useargparseorsys.argvtoacce

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

threading.Timer executes functions asynchronously after a specified delay without blocking the main thread, and is suitable for handling lightweight delays or periodic tasks. ①Basic usage: Create Timer object and call start() method to delay execution of the specified function; ② Cancel task: Calling cancel() method before the task is executed can prevent execution; ③ Repeating execution: Enable periodic operation by encapsulating the RepeatingTimer class; ④ Note: Each Timer starts a new thread, and resources should be managed reasonably. If necessary, call cancel() to avoid memory waste. When the main program exits, you need to pay attention to the influence of non-daemon threads. It is suitable for delayed operations, timeout processing, and simple polling. It is simple but very practical.
