使用 Main() return 值作为 python 脚本的参数

Using Main() return value as an argument for a python script

我希望我的 C++ 进程传递它们的 return 值以打开 python 脚本。

cpp 示例文件

int main()

{
   //do something
   //process is going to finish and is gonna return, for simplicity, 0
   //retval = 0, or whatever the return value is going to be 
   popen("mypython_script.py retval")
   return 0;
}

mypython_script.py

if __name__ == "__main__":
    cpp_retval = sys.argv[1]
    print(cpp_retval)

我不知道 C++ 文件是否可以按照描述发送它们的 return 值,但这只是我想要实现的一般行为。

我还可以控制每个 C++ 进程的父进程:它是另一个 python 脚本,负责打开 C++ 文件并在需要时终止它们的进程,所以如果你有一个涉及使用的解决方案父进程从 "cpp example file" 获取 return 值,这非常受欢迎

编辑:我忘了补充一点,我不能要求父 python 进程等待 C++ 程序 return 某些东西。我的程序中绝对不能有任何类型的 "waits"。

您可以从父 python 脚本捕获 C++ 程序的 return 值,如果您 运行 使用 cpp_retval = subprocess.call(...) 的 C++ 程序,或 cpp_retval = subprocesss.run(...).returncode (https://docs.python.org/3/library/subprocess.html).

然后您可以将其传递给另一个 python 脚本。所以,像这样:

cpp_retval = subprocess.call(["my_cpp_program.exe"])
subprocess.call(["my_python_script.py", str(cpp_retval)])

如果您想直接将值从 C++ 程序传递到 python 脚本,您可以这样做:

#include <cstdlib> // std::system
#include <string>

int main()
{
  const int retval = do_stuff();
  std::system((std::string("my_python_script.py") + ' ' + std::to_string(retval)).c_str());

  return retval;
}