Reading Python script from file.

I had issues at first loading my scripts from files. I based my original implementation off of the embedding example on the python wiki. This worked perfectly however when I tried to switch the run function for one that would run from a file I got less than acceptable results. So what I ended up doing is reading the scripts into memory and then passing the string to that function. This has at least one pitfall and that is memory usage. On larger files you may run into memory usage issues but other than that it seems to work ok. Below is a stripped down version for anyone else trying to work around similar issues.

EmbeddingPython



   1:  void RunScript(const char* filename)

   2:  {

   3:      FILE *file;

   4:          long fileSize=0;

   5:          char* buffer=NULL;

   6:   

   7:      try

   8:      {

   9:   

  10:              file = fopen(filename,"rb");

  11:   

  12:              if(file!=NULL)

  13:              {

  14:                      fseek(file,0,SEEK_END);

  15:                      fileSize = ftell(file);

  16:                      rewind(file);

  17:                      buffer = new char[fileSize];

  18:                      fread(buffer,fileSize,fileSize,file);

  19:              fclose(file);

  20:                      buffer[fileSize]='\0';

  21:                      handle<> ignored(( PyRun_String(buffer,

  22:                                       Py_file_input,

  23:                                       main_namespace.ptr(),

  24:                                       main_namespace.ptr() ) ));

  25:                      delete []buffer;

  26:   

  27:              }

  28:              else

  29:              {

  30:                      std::cout << "Script file could not be opened!" << std::endl;

  31:              }

  32:   

  33:          }

  34:          catch(error_already_set)

  35:          {

  36:              PyErr_Print();

  37:          }

  38:  }

Comments

Popular posts from this blog

VK9 - Milestone8 Completed

VK9 - Milestone13 Completed

VK9 - Milestone16 Completed