473,378 Members | 1,344 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,378 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 8463
Oralloy
985 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: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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...

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.