如何将 Python 中的变量传递回 C++?

How can I pass variables from Python back to C++?

我有 2 个文件 - 一个 .cpp 文件和一个 .py 文件。我使用 system("python something.py"); 到 运行 .py 文件,它必须获得一些输入。如何将输入传回 .cpp 文件?我不使用 Python.h 库,我有两个单独的文件。

system()是一个非常钝的锤子,不支持父进程和子进程之间的交互方式。

如果你想将信息从 Python 脚本传递回 C++ 父进程,我建议使用 python 脚本 print() 来标准输出你想要发回的信息到 C++,并让 C++ 程序解析 python 脚本的标准输出。 system() 不会让你这样做,但你可以使用 popen() 代替,如下所示:

#include <stdio.h>

int main(int, char **)
{
   FILE * fpIn = popen("python something.py", "r");
   if (fpIn)
   {
      char buf[1024];
      while(fgets(buf, sizeof(buf), fpIn))
      {
         printf("The python script printed:  [%s]\n", buf);
     
         // Code to parse out values from the text in (buf) could go here
      }
      pclose(fpIn);  // note:  be sure to call pclose(), *not* fclose()
   }
   else printf("Couldn't run python script!\n");

   return 0;
}

如果你想得到比这更详细的信息,你可能需要 embed a Python interpreter into your C++ program 然后你就可以直接调用 Python 函数并取回它们的 return 值作为 Python 个对象,但这是一项相当重要的工作,我猜你想避免。