开发者

Run a C++ Program from Django Framework

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 ?


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


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).


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜