Execute Python from a C++ program

[ permalink ] [ download ]
/* http://jimmyg.org/2007/09/30/buildout-a-c-executable-to-run-python-scripts/ */

/*
 * Buildout Launcher
 * +++++++++++++++++
 *
 * This application excutes a python script in the same directory as the
 * application. This is useful because it effectively turns a Python script
 * into a real executable which you can use on the #! line of other scripts.
 *
 * The script to be executed should have the same name as the the filename of
 * this compiled program but with a .py extension added to the end. The real
 * Python interpreter used to execute the script is dermined from the script's
 * #! line or /usr/bin/python is used as a fallback if no Python interpreter
 * can be found.
 *
 * The Python interpreters generated by Buildout are actually just Python
 * scripts so this application allows them to be run from a real executable.
 *
 * Compile this file with the following command:
 *
 *     g++ launcher.cc -o launcher
 *
 * Copyright James Gardner. MIT license. No warranty to the maximum extent
 * possible under the law.
 *
 */

#include <vector>
#include <string>
#include <unistd.h>
#include <fstream>

using namespace std;
int main(int argc,char *argv[])
{
    vector<string> args;
    int i;
    args.push_back("python");
    for (i=0;i<argc;i++)
        args.push_back(argv[i]);
    args[1] = strcat(argv[0], ".py");
    char *new_argv[argc+1];
    for (int i=0 ; i<argc+1 ; i++)  {
        new_argv[i] = (char *)args[i].c_str();
        //printf("i: %d, val: %s\n", i, new_argv[i]);
    }
    new_argv[argc+1] = NULL;
    vector<string> text_file;
    ifstream ifs(new_argv[1]);
    string temp;
    string temp_short;
    getline(ifs, temp);
    if (strncmp((char *)temp.c_str(), "#!", 2)) {
        /* default to /usr/bin/python if no #! header */
        temp_short = "/usr/bin/python";
    } else {
        temp_short = temp.substr(2,(temp.length()-2));
    }
    char python[temp_short.length()];
    strcpy(python, (char *)temp_short.c_str());
    //printf("%s\n", python);
    return execv(python, new_argv);
}
hits counter