【问题标题】:execute .py file from c++从 C++ 执行 .py 文件
【发布时间】:2015-02-03 22:20:38
【问题描述】:

我正在使用 C++。我需要执行一个带有条件的python脚本

int main()
{
    if(op==1)
    {
        RUN("MUL.py"); // execute MUL.py script
    }
    else
    {
        RUN("DIV.py"); // execute DIV.py script
    }

    return 0;
}

我可以这样做:

Py_Initialize();
PyRun_SimpleString(code);
Py_Finalize();

在这里,我必须制作一个字符串。那我得跑了。

但是,我不想这样做。我已经有一个 .py 文件。我只需要运行那个文件。

类似:py_run(MUL.py)

我的 python 代码会为我做一些大的计算。这会将答案写入文件中。我将在我的 c++ 代码中从该文件中读取该答案。

我该怎么做?

【问题讨论】:

  • 首先想到的是system("MUL.py");

标签: python c++


【解决方案1】:

PyRun_SimpleFile 函数系列。例如:

FILE *fd = fopen("MUL.py", "r");
PyRun_SimpleFileEx(fd, "MUL.py", 1); // last parameter == 1 means to close the
                                     // file before returning.

另请参阅documentation

【讨论】:

  • 我猜你的编译器在其包含和链接器路径中没有 python 目录。将python-config --cflags 的输出添加到编译器标志,将python-config --ldflags 的输出添加到链接器标志。
  • :( compiler flagslinker flags 我不知道。我应该在哪里找到这些?我在 Windows 中使用 Visual Studio
  • msdn.microsoft.com/en-us/library/ee855621.aspx。您必须将带有 python 头的目录放在包含路径中,将带有 python 库的目录放在链接器路径中。然后,您必须将库(可能是 python.lib 或 python2.7.lib 左右,但我从未在 Windows 下链接到 python)添加到项目选项中的附加链接器输入(在“链接器”下)。另请注意,<Python.h> 应在任何系统标头之前为 #included。
猜你喜欢
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 2019-09-27
  • 2018-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多