implement functions to execute arbitrary python code from strings or files and recast the python source keyword through using them.

This commit is contained in:
Axel Kohlmeyer
2017-05-11 22:39:08 -04:00
parent 27a6371f9b
commit d84f8898b7
4 changed files with 53 additions and 14 deletions

View File

@ -122,26 +122,17 @@ void PythonImpl::command(int narg, char **arg)
// if source is only keyword, execute the python code
if (narg == 3 && strcmp(arg[1],"source") == 0) {
int err;
PyGILState_STATE gstate = PyGILState_Ensure();
// if argument string is file, open it
// otherwise process string as python code
int err = 0;
FILE *fp = fopen(arg[2],"r");
if (fp == NULL)
err = PyRun_SimpleString(arg[2]);
err = execute_string(arg[2]);
else
err = PyRun_SimpleFile(fp,arg[2]);
err = execute_file(arg[2]);
if (err) {
PyGILState_Release(gstate);
error->all(FLERR,"Could not process Python source command");
}
if (fp) fclose(fp);
PyGILState_Release(gstate);
if (err) error->all(FLERR,"Could not process Python source command");
return;
}
@ -503,6 +494,32 @@ int PythonImpl::create_entry(char *name)
return ifunc;
}
/* ---------------------------------------------------------------------- */
int PythonImpl::execute_string(char *cmd)
{
PyGILState_STATE gstate = PyGILState_Ensure();
int err = PyRun_SimpleString(cmd);
PyGILState_Release(gstate);
return err;
}
/* ---------------------------------------------------------------------- */
int PythonImpl::execute_file(char *fname)
{
FILE *fp = fopen(fname,"r");
if (fp == NULL) return -1;
PyGILState_STATE gstate = PyGILState_Ensure();
int err = PyRun_SimpleFile(fp,fname);
PyGILState_Release(gstate);
if (fp) fclose(fp);
return err;
}
/* ------------------------------------------------------------------ */
void PythonImpl::deallocate(int i)

View File

@ -29,6 +29,8 @@ class PythonImpl : protected Pointers, public PythonInterface {
int find(char *);
int variable_match(char *, char *, int);
char *long_string(int);
int execute_string(char *);
int execute_file(char *);
private:
int ninput,noutput,length_longstr;

View File

@ -97,3 +97,19 @@ char * Python::long_string(int ifunc)
init();
return impl->long_string(ifunc);
}
/* ------------------------------------------------------------------ */
int Python::execute_string(char *cmd)
{
init();
return impl->execute_string(cmd);
}
/* ------------------------------------------------------------------ */
int Python::execute_file(char *fname)
{
init();
return impl->execute_file(fname);
}

View File

@ -26,6 +26,8 @@ public:
virtual int find(char *) = 0;
virtual int variable_match(char *, char *, int) = 0;
virtual char * long_string(int ifunc) = 0;
virtual int execute_string(char *) = 0;
virtual int execute_file(char *) = 0;
};
class Python : protected Pointers {
@ -38,6 +40,8 @@ public:
int find(char *);
int variable_match(char *, char *, int);
char * long_string(int ifunc);
int execute_string(char *);
int execute_file(char *);
bool is_enabled() const;
void init();