python - 使用 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 而没有调用脚本。
任何帮助是极大的赞赏。谢谢!
解决方案
如果您在调用之前在结构的成员中设置了SEE_MASK_NO_CONSOLE
标志,那么 Python 解释器将继承您的 C++ 程序的控制台(假设它附加到一个控制台),而不是为 Python 解释器创建新的控制台。这样,您的 C++ 程序将完全控制控制台何时关闭。当 Python 解释器退出时,控制台不会自动关闭,只要您的 C++ 程序仍在运行并附加到控制台。fMask
SHELLEXECUTEINFO
ShellExecuteEx
如果您的 C++ 程序尚未连接到控制台,则可以通过调用函数将其连接到控制台AllocConsole
。您应该在调用之前执行此操作ShellExecuteEx
。
推荐阅读
- spring - Spring Boot 中的事务测试 - 如何获取当前会话?
- plot - GNUPLOT 中的层次轴
- javascript - 为什么解决冲突的不同方法不会给出与原始方法相同的结果
- c - C中的*(int *)和(int *)有什么区别?
- c - 通过管道将多个 const char* 路径连接在一起
- windows - 从控制面板获取用户首选语言列表的正确方法是什么?
- flutter - AWS Amplify,初始化失败
- c# - 从服务中读取本地安全策略
- go - 为什么 Go Programming 将任何以零开头的数字视为八进制,我该如何防止这种情况发生?
- rust - 如何在赋值时解决“预期结构,找到类型参数”?