{"id":61402,"date":"2024-04-27T17:09:30","date_gmt":"2024-04-27T17:09:30","guid":{"rendered":"https:\/\/www.askpython.com\/?p=61402"},"modified":"2025-04-10T20:30:56","modified_gmt":"2025-04-10T20:30:56","slug":"calling-python-scripts-from-c","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/examples\/calling-python-scripts-from-c","title":{"rendered":"Calling Python Scripts from C: A Step-by-Step Guide Using Python\/C API"},"content":{"rendered":"\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><em>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.<\/em><\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\"><em>Also Read: <a href=\"https:\/\/www.askpython.com\/python\/examples\/python-correlation-basics\" data-type=\"post\" data-id=\"59806\">A Basic Intro to Python Correlation<\/a><\/em><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Using the Python\/C API to Call Python Scripts from C<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here we don&#8217;t need to install any modules separately. Python\/C API comes with Python packages and often provides header files like &#8220;Python.h&#8221;.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step-by-Step Guide to Implementing Python in C<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Creating the Python File with Sample Functions<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Before we start implementing Python functions from C. Let&#8217;s build a Python script that will hold two types of functions.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ndef fun1():\n    print(&quot;I am Function1&quot;)\n    return 0\n\ndef fun2(x):\n    print(&quot;I am Function2&quot;)\n    return x\n<\/pre><\/div>\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"578\" height=\"200\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/image-4.png\" alt=\"code1\" class=\"wp-image-61956\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/image-4.png 578w, https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/image-4-300x104.png 300w\" sizes=\"auto, (max-width: 578px) 100vw, 578px\" \/><figcaption class=\"wp-element-caption\">code1<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Setting Up the C\/C++ File for Python Integration<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Next, we need to add a Python library to our &#8220;.c&#8221; file. Add the following header file because it includes all the Python objects and functions.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#include &lt;Python.h&gt;\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nPy_Initialize();\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Next, you must set the path to the Python library you wish to import into your application. Use &#8220;PySys_SetPath&#8221; for setting the path. In brackets add the path to your file.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nPySys_SetPath(&quot;\/desktop\/Python\/Sample&quot;);\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><em>Also Read: <a href=\"https:\/\/www.askpython.com\/python-modules\/flask\/run-flask-app-python3\" data-type=\"post\" data-id=\"61477\">Running a Flask Application with Python3: A Step-by-Step Guide<\/a><\/em><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Creating Python Objects in C<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Now we will create an instance of a Python object using PyObject.  <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nPyObject *name, *load_module,*func,*callfunc, *args;\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Here the instance holds different parameters like &#8220;name&#8221; for storing the file&#8217;s name and the &#8216;load_module&#8217; will store the imported Python file. Secondly the &#8216;func&#8217; will store the name of the Python function to be called and &#8216;callfunc&#8217; will call the Python function as per the stored value.  Lastly, the &#8216;args&#8217; is used to provide arguments inside the function.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Calling Python Functions from C Code<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s first call the function &#8216;fun1&#8217; from the Python file. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nname = PyUnicode_FromString(&quot;sample&quot; );  \nload_module = PyImport_Import(name);      \nfunc= PyObject_GetAttrString(load_module,(char *)&quot;fun1&quot;);\ncallfunc=PyObject_CallObject(func,NULL);\ndouble f1output = PyFloat_AsDouble(callfunc);\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Here we will understand code line by line. The &#8216;name&#8217; parameter is used to store the file&#8217;s name (&#8216;Sample&#8217;) in the form of a String. The &#8216;load_module&#8217; will store the imported Python file and the &#8216;func&#8217; will store the function&#8217;s name to be called. The &#8216;callfunc&#8217; is used to call the Python function and &#8216;fun1_out&#8217; is used to store the value returned by the function.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now for calling a function with parameters, you must add &#8216;args&#8217; parameter before calling the function.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nfunc= PyObject_GetAttrString(load_module,(char *)&quot;fun2&quot;);\nargs = PyTuple_Pack(1,PyFloat_FromDouble(13));\ncallfunc=PyObject_CallObject(func,NULL);\ndouble f2output = PyFloat_AsDouble(callfunc);\n<\/pre><\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>Finalizing the Python Interpreter<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">At last, finalise the Python interpreter and display the output using the &#8216;printf&#8217; function. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nPy_Finalize();\nprintf(&quot;%f\\n&quot;,f1output);\nprintf(&quot;%f\\n&quot;,f2output);\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">After creating the whole file it must look like this:<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"677\" height=\"580\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/image-3.png\" alt=\"Code2\" class=\"wp-image-61955\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/image-3.png 677w, https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/image-3-300x257.png 300w\" sizes=\"auto, (max-width: 677px) 100vw, 677px\" \/><figcaption class=\"wp-element-caption\">Code2<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">For the compilation, I suggest using the &#8216;cmake&#8217; compilation method through the command prompt. It will provide you with the output as follows:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nI am Function1\nI am Function2\n0\n13.0\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">In this output, we can see that the functions are compiled first and thereafter the returned values are printed together.<\/p>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1713033712478\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">What is the advantage of calling Python code from C?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>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.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1713034170515\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">What are the different ways of compiling Python code from C?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>We can use the &#8216;cmake&#8217; method which involves adding the Python interpreter details and calling the same file from the command prompt. Another method is the &#8216;g++&#8217; method which can help us compile Python code from C\/C++ files.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n\n\n<h2 class=\"wp-block-heading\">Summing Up: Integrating Python Scripts in C Applications<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Further, it&#8217;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 &#8216;cmake&#8217; or use the &#8216;g++&#8217; technique through the command prompt to get outputs.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/docs.python.org\/3\/extending\/extending.html\" target=\"_blank\" rel=\"noopener\">https:\/\/docs.python.org\/3\/extending\/extending.html<\/a><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/stackoverflow.com\/questions\/1056051\/how-do-you-call-python-code-from-c-code\" target=\"_blank\" rel=\"noopener\">https:\/\/stackoverflow.com\/questions\/1056051\/how-do-you-call-python-code-from-c-code<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>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 [&hellip;]<\/p>\n","protected":false},"author":78,"featured_media":63880,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[],"class_list":["post-61402","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-examples"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/61402","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/78"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=61402"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/61402\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/63880"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=61402"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=61402"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=61402"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}