简体   繁体   English

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

[英]Executing Python Script from C++ program in Windows XP

I am attempting to execute a python script from a C++ program. 我正在尝试从C ++程序执行python脚本。 The problem that I am having is that I am unable to execute my python script. 我遇到的问题是我无法执行我的python脚本。

If I take out the lpParameter value by setting it equal to NULL everything works fine, my program launches the python terminal and then my program finishes when I exit the python terminal. 如果我通过将lpParameter值设置为NULL来取出它,则一切正常,我的程序启动python终端,然后当我退出python终端时,我的程序完成。

I have a feeling that it has to do with the lpParameters field separating arguments with spaces, so I attempted to the entire python script in escaped quotation marks. 我感觉这与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;
}

What happens when I launch this code is my program runs, quickly pops up another terminal that is quickly gone and then my original terminal says the task is complete. 当我启动此代码时,程序将运行,迅速弹出另一个终端,该终端很快消失,然后我的原始终端说任务已完成。 In reality though the python script that I specified is never executed. 实际上,尽管我指定的python脚本从未执行过。

Not really an answer, but too long for a comment. 并非真正的答案,但评论太久。

The problem with those kind of execution in a new window, it the as soon as the program has ended the window is closed. 这种在新窗口中执行的问题是,一旦程序结束窗口就会关闭。 As a window has been opened, it is likely from the point of view of the launching program all is fine. 当打开一个窗口时,从启动程序的角度来看,可能一切都很好。

My advice here would be to use a cmd /k that forces a window to keep opened after the end of the program : 我的建议是在程序结束后使用cmd /k强制窗口保持打开状态:

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

At least if there is an error anywhere, you will be given a chance to see it. 至少如果某个地方有错误,您将有机会看到它。

Turns out the issue was with permissions and setting this parameter: 原来问题出在权限和设置此参数上:

shExecInfo.lpVerb = "runas";

Instead I left it 相反,我离开了

shExecInfo.lpVerb = NULL;

and also filled in the directory parameter and it is working now. 并填写了directory参数,现在可以使用了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM