tags:

views:

115

answers:

5

I need to run a C++ Program from Django Framework. In a sense, I get inputs from UI in views.py . Once I have these inputs, I need to process the input using my C++ program and use those results. Is it possible ?

+6  A: 

Compile that C++ program to executable and call with subprocess module from python

S.Mark
+1  A: 

You can use swig to create a C++ module that can be imported in python. An alternative is boost::python (but personnaly, I prefer swig).

Tristram Gräbener
A: 

One way of doing this would be to use os.popen. Assuming your C++ executable is in the system wide path and is named mycpp, you would do something like:

results = os.popen('mycpp %s' % user_input).read()

However, this could get computationally expensive real fast if you're invoking this command often 'cause os.popen basically forks off a subprocess. Also, as noted in the docs, it's been deprecated since Python 2.6 so proceed with caution.

Rishabh Manocha
Not only is it deprecated, there's no reason to use it. The exact same functionality is available in the `subprocess` module, as mentioned in S.Mark's answer.
Travis Bradshaw
A: 

But Where do I store my executable cpp file ? In the Django App or on the server ? And please give a small snippet for example .

vishwanath Katharki
Please use the comment feature, rather than replying with a new answer. It's hard to know where your questions are directed.
greyfade
A: 

Assuming you are on *nix, compile your C++ program and store it somewhere on your system, say /home/rishabh/myexe.

Now from your django app call the executable using commands module:

import commands

status, res = commands.getstatusoutput("/home/rishabh/myexe")

# status contains process status (0 for success, non-zero for unsuccesful termination) and res contains the output of the process
sharjeel