473,396 Members | 2,154 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,396 developers and data experts.

Three ways to run Python programs from C

kudos
127 Expert 100+
One question, that often comes up is: How to call Python from my C program? There are numerous ways, so let us review three of them.

System Approach

We could call Python from C program by using the system function, which basically means, we do need have an already written python program, or you would need to make a C program write a python program to disk. Here is a quick example:

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2.  
  3. int main(){
  4.  
  5. char *prg = (char*)"print \"hello from python\"\n";
  6. FILE *f= (FILE*)fopen("test2.py","w");
  7. fprintf(f, prg);
  8. fclose(f);
  9.  
  10. system("python test2.py");
  11.  
  12. }
  13.  
Let's assume that the program was saved as test2.c, then you would compile it the following way:

gcc test1.c

Then you would run it like this:

./a.out

The bad thing about this approach is; what if we were to do anything in python, and we wanted Python to output something, which we then could process in C? We could make our Python program write to file, then we could have the C program read the outputted file from the Python program, but then you have to make some modifications to your python program and you would have a lot of files with result floating around on your harddrive (like there isn't enough there already!)


Process Approach

Let's make a toy program, we want to add two number in Python, which are given to us from a C program. So the C program would supply us with the two numbers, the two numbers would then be sent to a Python program and the result would be written from the C program through the printf command.

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main(){
  5. int number1 = 10;
  6. int number2 = 32;
  7. int number3 = -1;
  8.  
  9. /* the python program as a C string */
  10. char *prg = (char*)"import sys\nprint int(sys.argv[1])+int(sys.argv[2])\n";
  11. /* make a C string which call Python */
  12. char *input = (char*)malloc(sizeof(100)*sizeof(char));
  13. /* a C string which will store the results */
  14. char *input2 = (char*)malloc(sizeof(100)*sizeof(char));
  15. FILE *f= (FILE*)fopen("test2.py","w");
  16. fprintf(f, prg);
  17. fclose(f);
  18. sprintf(input,"python test2.py %d %d",number1,number2);
  19. f = popen(input,"r");
  20. fgets(input2,100,f);
  21. fclose(f);
  22. number3 = atoi(input2);
  23. printf("%d\n",number3+10);
  24.  
Here we use popen to open a process, and in this case, the process happens to be the python interpreter running the program which we defined as a C string. We can read the result of our the process, which in our case is going to be 42. Then we convert this string into an int with atoi.

Let's assume that the program was saved as test2.c, then you would compile it the following way:

gcc test2.c

Then you would run it like this:

./a.out

Embedded Approach

What if you device didn't have an operating system? Or maybe you don't want your program to interfere with your operating system? One possibility is to embed python into your C program. Now, what does "embed" actually mean? Well, it means, make the interpreter part of your C program

First, what kind of system are you on? (you probably would stop somewhere in the last section in Windows, because I don't think popen is called popen in the Windows api).

Let's assume that you are using Ubuntu or something similar. First, we need to Figure out the flags for compiling and embedding Python into your C program. Where are the include files, and where are the library file?

I start by figuring out what kind of Python I run on my system

python --version

Which returns :

Python 2.6.5

Now I want to figure out where the .h file is, so I type:

locate Python.h

which returns :

/usr/include/python2.6/Python.h

Then I want to find the library file(which basically is the python interpreter):

locate libpython2.6.a

/usr/lib/python2.6/config/libpython2.6.a

Then I got all the things I need, now, let's make sure that we get this works before I do anything else.

We start by making an empty C program


Expand|Select|Wrap|Line Numbers
  1. #include <Python.h>
  2. #include <stdio.h>
  3.  
  4. int main(){
  5.  
  6. }
Do we get this to compile? Let's save it as test3.c

gcc -I/usr/include/python2.6/ -L/usr/lib/python2.6/config/ -lpython2.6 test3.c

Did it work? If yes, then let's continue to make an interesting C with Python program in test3.c. The program should do what it did earlier; we have two numbers (number1 and number2), we want python to add these two numbers, then we want to get the result of the addition in Python and place it in a variable called number3 in C

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <Python.h>
  3.  
  4. int main(){
  5. int number1 = 10;
  6. int number2 = 32;
  7. Py_Initialize();
  8. char *input = (char*)malloc(sizeof(100)*sizeof(char));
  9. sprintf(input,"number3 = %d + %d",number1,number2);
  10. PyRun_SimpleString(input);
  11. PyObject * module = PyImport_AddModule("__main__");
  12. PyObject * dictionary = PyModule_GetDict(module);
  13. PyObject * result = PyDict_GetItemString(dictionary, "number3");
  14. long number3 = PyInt_AS_LONG(result);
  15. printf("%d\n",(int)number3);
  16. Py_Finalize();
  17. }
  18.  
You would typically run it as:

./a.out

In this case, we do not need to call the Python as a separate process, because Python is already part of your C program. Now which one should you use? The cons of the embedded version you have to bare careful when you compile your C program. The pros is that you don't interfere with the processes on your computer, write files to your harddrive etc.
Jun 9 '13 #1
1 8474
Oralloy
988 Expert 512MB
It seems to me that you would use each of the solutions to solve a particular category of problem.

BTW, I do not like the "system" approach, as you are constrained to creating a string that is exactly compatible with Bash (or sh) command line input.

The fork() and exec() approach is probably better. If for no other reason than it does not require encoding of arguments.

The "process approach" has the same issues as the "system" approach.

Running python as an embedded interpreter is fine, but what is the point?
  • If all you want to do is run Python, why bother with C at all?
  • This might be valuable when you are dynamically creating non-trivial Python, but few applications will do such.
  • This is not valuable if all you are doing is creating python to match a few parameters. Included/excluded code blocks can be guarded in a fixed program much easier.

The bottom line is that executing a sub-process only makes sense when:
  • The target language lets you solve a problem easily, which would otherwise be difficult in C.
  • You do not have access to the source of the sub-process.
  • You do not want to re-implement an existing, debugged program in C. (which is quite reasonable).
  • Parallel execution is valuable - the sub-process does something while the C process does something else.

The model you will select depends strongly on your goals. Do you need just the output from Python based on invocation parameters, or do you want to transfer data back and forth between the two?

Your question is really good, although there is no explicit answer.

Cheers!
Orally
Sep 24 '16 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Roberts | last post by:
Hi, I managed to get the Java extension working on php 4.3.10 after following various bits of advice from http://www.thelinuxpimp.com/main/modules.php?op=modload&name=News&file=article&sid=419...
5
by: MiLF | last post by:
Is it possible to write a Audio CD Player by using python only?
1
by: Harlin | last post by:
Has anyone had any success using py2exe with anything you've written using the Python .NET implementation? (This is the one from the Zope website -- not ActiveState). I seem to be having trouble...
0
by: Christophe | last post by:
hi, I work alone but still use VSS for de version feature.(Version 6.0d build 9848) When I load a project from the start page that is a VSS project, I can't open de option window in de tool menu...
8
by: Joakim Persson | last post by:
Hello all. I am involved in a project where we have a desire to improve our software testing tools, and I'm in charge of looking for solutions regarding the logging of our software (originating...
29
by: 63q2o4i02 | last post by:
Hi, I'm interested in using python to start writing a CAD program for electrical design. I just got done reading Steven Rubin's book, I've used "real" EDA tools, and I have an MSEE, so I know what...
3
by: Joost | last post by:
Hi guys, I have couple of simple python based active server pages that make use of httplib2 which uses gzip.py. IIS, however, also has a gzip.dll located at the iis/inetsrv path. When using ASP...
53
by: Vicent Giner | last post by:
Hello. I am new to Python. It seems a very interesting language to me. Its simplicity is very attractive. However, it is usually said that Python is not a compiled but interpreted programming...
1
by: TP | last post by:
Hi everybody, All my problem is in the title. If I try: $ python -c 'print "foo",' It does not change anything, surely because the line return is added by "python -c".
0
by: Venky K Shankar | last post by:
On Sunday 20 July 2008 12:08:49 am Lamonte Harris wrote: you can execute OS system call. here i execute ps -ef and grep the required process name (or you can grep by pid on that particular...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.