【问题标题】:Run a C++ Program from Django Framework从 Django 框架运行 C++ 程序
【发布时间】:2010-01-19 05:27:42
【问题描述】:

我需要从 Django 框架运行 C++ 程序。从某种意义上说,我从 views.py 中的 UI 获得输入。获得这些输入后,我需要使用我的 C++ 程序处理输入并使用这些结果。有可能吗?

【问题讨论】:

    标签: c++ python django


    【解决方案1】:

    将该 C++ 程序编译为可执行并使用来自 python 的 subprocess 模块调用

    【讨论】:

      【解决方案2】:

      您可以使用 swig 创建一个可以在 python 中导入的 C++ 模块。 另一种选择是 boost::python (但就我个人而言,我更喜欢 swig)。

      【讨论】:

        【解决方案3】:

        一种方法是使用os.popen。假设您的 C++ 可执行文件位于系统范围的路径中并命名为 mycpp,您将执行以下操作:

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

        但是,如果您经常调用此命令,这可能会在计算上变得非常昂贵,因为os.popen 基本上会分叉出一个子进程。此外,正如文档中所述,它自 Python 2.6 以来已被弃用,因此请谨慎操作。

        【讨论】:

        • 它不仅已被弃用,而且没有理由使用它。如 S.Mark 的回答中所述,subprocess 模块中提供了完全相同的功能。
        【解决方案4】:

        假设您在 *nix 上,编译您的 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
        

        【讨论】:

          猜你喜欢
          • 2011-10-17
          • 2013-04-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-05-03
          相关资源
          最近更新 更多