首页 > 解决方案 > 使用 ShellExecuteEx 从 c++ 打开 python 控制台时关闭

问题描述

我必须从 c++ 打开一个 python 脚本。为此,我决定使用 ShellExecuteEx,如下所示:

  SHELLEXECUTEINFO ShExecInfo = { 0 };
  ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
  ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
  ShExecInfo.hwnd = NULL;
  ShExecInfo.lpVerb = NULL;
  ShExecInfo.lpFile = "python";
  ShExecInfo.lpParameters = strParams.c_str();
  ShExecInfo.lpDirectory = NULL;
  ShExecInfo.nShow = SW_NORMAL;
  ShExecInfo.hInstApp = NULL;
  ShellExecuteEx(&ShExecInfo);
  WaitForSingleObject(ShExecInfo.hProcess, INFINITE);
  CloseHandle(ShExecInfo.hProcess);
  size_t exeResult = (size_t)ShExecInfo.hInstApp;
  // check if the executable ran
  if (exeResult <= 32)
  {

然而,python 脚本结束时没有机会看到输出错误/回溯:

if __name__ == "__main__":
    f = open("python_log.txt", "w")
    f.write("hello")
    
    try:
        main()
    except Exception as e:
        print("An exception occurred", str(e))
        f.write(str(e))
        var = traceback.format_exc()
        print(var)
        f.write(var)
        
    f.close()
    wait = input("Press Enter to exit.")

我不知道还要添加什么或如何查看由 c++ 代码调用的 python 脚本的输出。我考虑过运行 cmd 并从那里启动 py 脚本,这样我就有了输出,但是我没有找到在 c++ 中实现它的方法,它只是启动 cmd 而没有调用脚本。

任何帮助是极大的赞赏。谢谢!

标签: pythonc++winapi

解决方案


如果您在调用之前在结构的成员中设置了SEE_MASK_NO_CONSOLE标志,那么 Python 解释器将继承您的 C++ 程序的控制台(假设它附加到一个控制台),而不是为 Python 解释器创建新的控制台。这样,您的 C++ 程序将完全控制控制台何时关闭。当 Python 解释器退出时,控制台不会自动关闭,只要您的 C++ 程序仍在运行并附加到控制台。fMaskSHELLEXECUTEINFOShellExecuteEx

如果您的 C++ 程序尚未连接到控制台,则可以通过调用函数将其连接到控制台AllocConsole。您应该在调用之前执行此操作ShellExecuteEx


推荐阅读