简体   繁体   中英

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 ?

将C ++程序编译为可执行文件并使用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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM