Calling Python Scripts from C: A Step-by-Step Guide Using Python/C API

Featured_image

This article explores how to call Python scripts from a C application using the Python/C API. It provides a step-by-step guide on setting up the API, creating Python and C files, initializing the interpreter, creating Python objects, calling Python functions from C, and finalizing the interpreter. The article also discusses the advantages of integrating Python code in C and different compilation methods.

Also Read: A Basic Intro to Python Correlation

Using the Python/C API to Call Python Scripts from C

Before calling a Python program from C, you should build a way for both to interact. This can be made possible using Python/C API. What it does is that it simply allows C code to create, manipulate and integrate Python objects, functions and libraries.

Here we don’t need to install any modules separately. Python/C API comes with Python packages and often provides header files like “Python.h”.

Step-by-Step Guide to Implementing Python in C

  • Creating the Python File with Sample Functions

Before we start implementing Python functions from C. Let’s build a Python script that will hold two types of functions.

def fun1():
    print("I am Function1")
    return 0

def fun2(x):
    print("I am Function2")
    return x
code1
code1

Here we have created functions with and without parameters to help with implementation. The first function will return 0 and the second will return the argument value passed.

  • Setting Up the C/C++ File for Python Integration

Next, we need to add a Python library to our “.c” file. Add the following header file because it includes all the Python objects and functions.

#include <Python.h>

The first foot towards implementing Python from C is to initialize the interpreter. The interpreter is nothing but a device used to read your code and detect errors based on analysis. Thus initialize the Python interpreter by adding the following line of code inside the main function.

Py_Initialize();

Next, you must set the path to the Python library you wish to import into your application. Use “PySys_SetPath” for setting the path. In brackets add the path to your file.

PySys_SetPath("/desktop/Python/Sample");

Also Read: Running a Flask Application with Python3: A Step-by-Step Guide

  • Creating Python Objects in C

Now we will create an instance of a Python object using PyObject.

PyObject *name, *load_module,*func,*callfunc, *args;

Here the instance holds different parameters like “name” for storing the file’s name and the ‘load_module’ will store the imported Python file. Secondly the ‘func’ will store the name of the Python function to be called and ‘callfunc’ will call the Python function as per the stored value. Lastly, the ‘args’ is used to provide arguments inside the function.

  • Calling Python Functions from C Code

Let’s first call the function ‘fun1’ from the Python file.

name = PyUnicode_FromString("sample" );  
load_module = PyImport_Import(name);      
func= PyObject_GetAttrString(load_module,(char *)"fun1");
callfunc=PyObject_CallObject(func,NULL);
double f1output = PyFloat_AsDouble(callfunc);

Here we will understand code line by line. The ‘name’ parameter is used to store the file’s name (‘Sample’) in the form of a String. The ‘load_module’ will store the imported Python file and the ‘func’ will store the function’s name to be called. The ‘callfunc’ is used to call the Python function and ‘fun1_out’ is used to store the value returned by the function.

Now for calling a function with parameters, you must add ‘args’ parameter before calling the function.

func= PyObject_GetAttrString(load_module,(char *)"fun2");
args = PyTuple_Pack(1,PyFloat_FromDouble(13));
callfunc=PyObject_CallObject(func,NULL);
double f2output = PyFloat_AsDouble(callfunc);
  • Finalizing the Python Interpreter

At last, finalise the Python interpreter and display the output using the ‘printf’ function.

Py_Finalize();
printf("%f\n",f1output);
printf("%f\n",f2output);

After creating the whole file it must look like this:

Code2
Code2

For the compilation, I suggest using the ‘cmake’ compilation method through the command prompt. It will provide you with the output as follows:

I am Function1
I am Function2
0
13.0

In this output, we can see that the functions are compiled first and thereafter the returned values are printed together.

What is the advantage of calling Python code from C?

While developing applications, we often face computationally intensive tasks like detecting weather patterns or analysing large datasets. Thus you can create an application in Python and call its functions in C code to increase efficiency and optimise the performance of the software in real-time.

What are the different ways of compiling Python code from C?

We can use the ‘cmake’ method which involves adding the Python interpreter details and calling the same file from the command prompt. Another method is the ‘g++’ method which can help us compile Python code from C/C++ files.

Summing Up: Integrating Python Scripts in C Applications

To sum up, you can say that integrating Python code in C language helps us to take advantage of both languages. As C/C++ is more compatible with hardware and Python is easy for users to interact with, thus it opens different levels of opportunities.

Further, it’s easy to call Python files in C because Python libraries help us create Python objects that can import files into multiple software. It comes with built-in functions to call methods into other source codes. Lastly, we can compile the whole C file by ‘cmake’ or use the ‘g++’ technique through the command prompt to get outputs.

References

https://docs.python.org/3/extending/extending.html

https://stackoverflow.com/questions/1056051/how-do-you-call-python-code-from-c-code