在 Windows XP 中从 C++ 程序执行 Python 脚本

Executing Python Script from C++ program in Windows XP

我正在尝试从 C++ 程序执行 python 脚本。我遇到的问题是我无法执行 python 脚本。

如果我通过将 lpParameter 值设置为 NULL 来取出它,一切正常,我的程序启动 python 终端,然后当我退出 python 终端时我的程序结束。

我觉得它与 lpParameters 字段有关,用空格分隔参数,所以我尝试将整个 python 脚本放在转义引号中。

#include "windows.h"
#include "shellapi.h"
#include <iostream>

using namespace std;

int main()
{
    cout<<"About to execute the shell command";

    SHELLEXECUTEINFO shExecInfo;
    shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
    shExecInfo.fMask = NULL;
    shExecInfo.hwnd = NULL;
    shExecInfo.lpVerb = "runas";
    shExecInfo.lpFile = "C:\Python25\python.exe";
    shExecInfo.lpParameters = "\"C:\Documents and Settings\John Williamson\My Documents\MyPrograms\PythonScripts\script.py\"";
    shExecInfo.lpDirectory = NULL;
    shExecInfo.nShow = SW_NORMAL;
    shExecInfo.hInstApp = NULL;
    ShellExecuteEx(&shExecInfo);


    return 0;
}

当我启动这段代码时发生的事情是我的程序运行,快速弹出另一个终端,但很快就消失了,然后我原来的终端说任务完成了。实际上,虽然我指定的 python 脚本从未执行过。

不是真正的答案,但评论太长了。

在新的 window 中执行这些类型的问题,一旦程序结束,window 就会关闭。由于已经打开了window,从启动程序的角度来看,可能一切都很好。

我的建议是使用 cmd /k 强制 window 在程序结束后保持打开状态:

shExecInfo.lpFile = "cmd";
shExecInfo.lpParameters = "/k C:\Python25\python.exe \"C:\Documents and Settings\John Williamson\My Documents\MyPrograms\PythonScripts\script.py\"";

至少如果有任何地方有错误,您将有机会看到它。

原来问题出在权限和设置此参数上:

shExecInfo.lpVerb = "runas";

相反,我离开了它

shExecInfo.lpVerb = NULL;

并且还填写了目录参数,现在可以使用了。