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

Executing Python Script from C++ program in Windows XP

本文关键字:执行 Python 脚本 程序 C++ Windows XP 中的      更新时间:2023-10-16

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

如果我通过将 lpParameter 值设置为空来取出它,一切正常,我的程序启动 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脚本从未执行过。

不是真正的答案,但太长了,无法发表评论。

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

我在这里的建议是使用一个cmd /k,强制窗口在程序结束后保持打开状态:

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;

并且还填写了目录参数,它现在可以工作了。