从Django框架中运行C++程序

4 投票
4 回答
5573 浏览
提问于 2025-04-15 18:11

我想在Django框架中运行一个C++程序。简单来说,我在views.py文件中从用户界面获取输入。一旦我得到了这些输入,我需要用我的C++程序来处理这些输入,然后使用处理后的结果。这样做可以吗?

4 个回答

0

假设你在使用*nix系统(比如Linux或Mac),首先需要编译你的C++程序,并把它存放在你电脑上的某个地方,比如说放在 /home/rishabh/myexe。

接下来,从你的Django应用程序中,可以使用命令模块来调用这个可执行文件:

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
1

你可以使用swig来创建一个可以在Python中导入的C++模块。还有一个替代方案是boost::python,但我个人更喜欢使用swig。

10

把那个C++程序编译成可执行文件,然后用Python里的subprocess模块来调用它。

撰写回答