【问题标题】:Taking an input from Python into a C++ program将 Python 的输入输入到 C++ 程序中
【发布时间】:2015-05-24 21:21:56
【问题描述】:

我正在开发一个程序,该程序包装了一个 C++ 程序,该程序使用 Python 突变核苷酸序列。我对 python 更熟悉,然后我对 C++ 更熟悉,使用 Python 解析数据文件对我来说更容易。

如何获取我在 Python 中解析的字符串,并将其用作 C++ 程序的输入? C++ 程序本身已经将用户输入的字符串作为输入。

【问题讨论】:

  • Wraps 究竟如何?
  • 你能解释一下你到底想要什么吗?以 Python 风格在 C++ 中解析,还是将 Python 解析的字符串解析为 C++?
  • 所以 C++ 文件接受一个字符串并根据已设置的一些规则更改该字符串。我正在使用 python 从在线数据文件中提取字符串,然后将其用作 C++ 文件中的输入,但我不知道该怎么做。
  • 假设您将数据编组为 JSON、CSV 或任何其他交换格式。然后,您必须使用 C++ 对其进行解析。为什么不简单地用 C++ 解析原始数据?

标签: python c++ wrapper extending


【解决方案1】:

您可以将您的 python 脚本作为一个单独的进程启动并获得其完整的输出。在 QT 中,您可以这样做,例如:

QString pythonAddress = "C:\\Python32\\python.exe";
QStringList params;

params << "C:\\your_script.py" << "parameter2" << "parameter3" << "parameter4";

p.start(pythonAddress, params);
p.waitForFinished(INFINITE);
QString p_stdout = p.readAll().trimmed(); // Here is the process output.

如果您不熟悉 QT,请使用特定于平台的流程操作技术或增强。看看这个:

How to execute a command and get output of command within C++?

How to create a process in C++ on Windows?

Execute a process and return its standard output in VC++

【讨论】:

    【解决方案2】:

    如果您的意思是从 Python 调用一个程序并对其输出做一些事情,那么您需要 subprocess 模块。

    如果您想将 C++ 函数直接暴露给 Python,那么我建议您查看 Boost.Python

    【讨论】:

      【解决方案3】:

      您想获取 Python 程序的输出并将其用作 C++ 程序的输入吗?

      你可以只使用外壳:

      python ./program.py | ./c_program  
      

      您想在 C++ 中执行 Python 程序并将输出作为字符串返回吗?
      可能有更好的方法来做到这一点,但这里有一个快速的解决方案:

      //runs in the shell and gives you back the results (stdout and stderr)
      std::string execute(std::string const& cmd){
          return exec(cmd.c_str());
      }
      std::string execute(const char* cmd) {
          FILE* pipe = popen(cmd, "r");
          if (!pipe) return "ERROR";
          char buffer[128];
          std::string result = "";
          while(!feof(pipe)) {
              if(fgets(buffer, 128, pipe) != NULL)
                  result += buffer;
          }
          pclose(pipe);
              if (result.size() > 0){
          result.resize(result.size()-1);
          }
          return result;
      }
      

      std::string results_of_python_program = execute("python program.py");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-12
        • 1970-01-01
        • 2013-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多