Executing Python Script from C++ program in Windows XP

618 views Asked by At

I am attempting to execute a python script from a C++ program. The problem that I am having is that I am unable to execute my python script.

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.

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.

#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.

2

There are 2 answers

0
Serge Ballesta On BEST ANSWER

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 :

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.

0
Matthew On

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.