| 1 |
// clang-format off |
| 2 |
/* |
| 3 |
PPEMBED, VERSION 2.0 |
| 4 |
AN ENHANCED PYTHON EMBEDDED-CALL INTERFACE |
| 5 |
|
| 6 |
Copyright 1996-2000, by Mark Lutz, and O'Reilly and Associates. |
| 7 |
Permission to use, copy, modify, and distribute this software |
| 8 |
for any purpose and without fee is hereby granted. This software |
| 9 |
is provided on an as is basis, without warranties of any kind. |
| 10 |
*/ |
| 11 |
|
| 12 |
#include <FCConfig.h> |
| 13 |
#include "PyTools.h" |
| 14 |
|
| 15 |
#include <stdarg.h> |
| 16 |
#include <string.h> |
| 17 |
#include <assert.h> |
| 18 |
#include <compile.h> |
| 19 |
#include <frameobject.h> |
| 20 |
#if PY_VERSION_HEX < 0x030b0000 |
| 21 |
#include <eval.h> |
| 22 |
#endif |
| 23 |
|
| 24 |
//NOLINTBEGIN |
| 25 |
/***************************************************************************** |
| 26 |
* RUN EMBEDDED OBJECT METHODS, ACCESS OBJECT ATTRIBUTES |
| 27 |
* handles attribute fetch, debugging, input/output conversions; |
| 28 |
* there is no module to reload here: assumes a known object; |
| 29 |
*****************************************************************************/ |
| 30 |
|
| 31 |
int |
| 32 |
PP_Run_Method(PyObject *pobject, const char *method, |
| 33 |
const char *resfmt, void *cresult, /* convert to c/c++ */ |
| 34 |
const char *argfmt, ... /* arg,... */ ) /* convert to python */ |
| 35 |
{ |
| 36 |
PyObject *pmeth = NULL, *pargs = NULL, *presult = NULL; |
| 37 |
va_list argslist; /* "pobject.method(args)" */ |
| 38 |
va_start(argslist, argfmt); |
| 39 |
|
| 40 |
Py_Initialize(); /* init if first time */ |
| 41 |
pmeth = PyObject_GetAttrString(pobject, method); |
| 42 |
if (pmeth == NULL) { /* get callable object */ |
| 43 |
va_end(argslist); |
| 44 |
return -1; /* bound method? has self */ |
| 45 |
} |
| 46 |
|
| 47 |
pargs = Py_VaBuildValue(argfmt, argslist); /* args: c->python */ |
| 48 |
va_end(argslist); |
| 49 |
|
| 50 |
if (pargs == NULL) { |
| 51 |
Py_DECREF(pmeth); |
| 52 |
return -1; |
| 53 |
} |
| 54 |
if (PP_DEBUG) /* debug it too? */ |
| 55 |
presult = PP_Debug_Function(pmeth, pargs); |
| 56 |
else |
| 57 |
presult = PyObject_CallObject(pmeth, pargs); /* run interpreter */ |
| 58 |
|
| 59 |
Py_DECREF(pmeth); |
| 60 |
Py_DECREF(pargs); |
| 61 |
|
| 62 |
return PP_Convert_Result(presult, resfmt, cresult); /* to C format */ |
| 63 |
} |
| 64 |
|
| 65 |
|
| 66 |
int |
| 67 |
PP_Get_Member(PyObject *pobject, const char *attrname, |
| 68 |
const char *resfmt, void *cresult) /* convert to c/c++ */ |
| 69 |
{ |
| 70 |
PyObject *pmemb = NULL; /* "pobject.attrname" */ |
| 71 |
Py_Initialize(); |
| 72 |
pmemb = PyObject_GetAttrString(pobject, attrname); /* incref'd */ |
| 73 |
return PP_Convert_Result(pmemb, resfmt, cresult); /* to C form, decrefs */ |
| 74 |
} |
| 75 |
|
| 76 |
|
| 77 |
int |
| 78 |
PP_Set_Member(PyObject *pobject, const char *attrname, |
| 79 |
const char *argfmt, ... /* arg,... */ ) /* convert to python */ |
| 80 |
{ |
| 81 |
int result = 0; |
| 82 |
PyObject *pval = NULL; |
| 83 |
va_list argslist; /* "pobject.attrname = v" */ |
| 84 |
va_start(argslist, argfmt); |
| 85 |
Py_Initialize(); /* init if first time */ |
| 86 |
pval = Py_VaBuildValue(argfmt, argslist); /* input: C->Python */ |
| 87 |
va_end(argslist); |
| 88 |
if (pval == NULL) |
| 89 |
return -1; |
| 90 |
result = PyObject_SetAttrString(pobject, attrname, pval); /* setattr */ |
| 91 |
Py_DECREF(pval); |
| 92 |
return result; |
| 93 |
} |
| 94 |
|
| 95 |
|
| 96 |
/***************************************************************************** |
| 97 |
* RUN EMBEDDED MODULE FUNCTIONS |
| 98 |
* handles module (re)import, debugging, input/output conversions; |
| 99 |
* note: also useful for calling classes (and C type constructors) at the |
| 100 |
* top-level of a module to make Python instances: use class-name (or type |
| 101 |
* constructor function name) and 'O' result convert-code to get raw object; |
| 102 |
* use argfmt="()" for no args, cresult='NULL' for no result (procedure); |
| 103 |
* New tools: support for calling known Python objects directly; |
| 104 |
*****************************************************************************/ |
| 105 |
|
| 106 |
int |
| 107 |
PP_Run_Function(const char *modname, const char *funcname, /* load from module */ |
| 108 |
const char *resfmt, void *cresult, /* convert to c/c++ */ |
| 109 |
const char *argfmt, ... /* arg, arg... */ ) /* convert to python */ |
| 110 |
{ |
| 111 |
/* call a function or class in a module */ |
| 112 |
PyObject *func = NULL, *args = NULL, *presult = NULL; |
| 113 |
va_list argslist; |
| 114 |
va_start(argslist, argfmt); /* "modname.funcname(args)" */ |
| 115 |
|
| 116 |
func = PP_Load_Attribute(modname, funcname); /* may reload; incref'd */ |
| 117 |
if (func == NULL) { /* func or class or C type */ |
| 118 |
va_end(argslist); |
| 119 |
return -1; |
| 120 |
} |
| 121 |
args = Py_VaBuildValue(argfmt, argslist); /* convert args to python */ |
| 122 |
va_end(argslist); |
| 123 |
if (args == NULL) { /* args incref'd */ |
| 124 |
Py_DECREF(func); |
| 125 |
return -1; |
| 126 |
} |
| 127 |
if (PP_DEBUG && strcmp(modname, "pdb") != 0) /* debug this call? */ |
| 128 |
presult = PP_Debug_Function(func, args); /* run in pdb; incref'd */ |
| 129 |
else |
| 130 |
presult = PyObject_CallObject(func, args); /* run function; incref'd */ |
| 131 |
|
| 132 |
Py_DECREF(func); |
| 133 |
Py_DECREF(args); /* result may be None */ |
| 134 |
return PP_Convert_Result(presult, resfmt, cresult); /* convert result to C*/ |
| 135 |
} |
| 136 |
|
| 137 |
|
| 138 |
PyObject * |
| 139 |
PP_Debug_Function(PyObject *func, PyObject *args) |
| 140 |
{ |
| 141 |
int oops = 0, res = 0; |
| 142 |
PyObject *presult = NULL; |
| 143 |
|
| 144 |
/* expand tuple at front */ |
| 145 |
// it seems that some versions of python want just 2 arguments; in that |
| 146 |
// case, remove trailing 1 |
| 147 |
oops = _PyTuple_Resize(&args, (1 + PyTuple_Size(args))); |
| 148 |
oops |= PyTuple_SetItem(args, 0, func); |
| 149 |
if (oops) |
| 150 |
return NULL; /* "args = (funcobj,) + (arg,..)" */ |
| 151 |
|
| 152 |
res = PP_Run_Function( /* "pdb.runcall(funcobj, arg,..)" */ |
| 153 |
"pdb", "runcall", /* recursive run_function */ |
| 154 |
"O", &presult, |
| 155 |
"O", args); /* args already is a tuple */ |
| 156 |
return (res != 0) ? NULL : presult; /* errors in run_function? */ |
| 157 |
} /* presult not yet decref'd */ |
| 158 |
|
| 159 |
|
| 160 |
int |
| 161 |
PP_Run_Known_Callable(PyObject *object, /* func|class|method */ |
| 162 |
const char *resfmt, void *cresult, /* skip module fetch */ |
| 163 |
const char *argfmt, ... /* arg,.. */) /* convert args, result */ |
| 164 |
{ |
| 165 |
/* call a known callable object */ |
| 166 |
PyObject *args = NULL, *presult = NULL; |
| 167 |
va_list argslist; |
| 168 |
va_start(argslist, argfmt); /* "return object(args)" */ |
| 169 |
|
| 170 |
Py_Initialize(); |
| 171 |
args = Py_VaBuildValue(argfmt, argslist); /* convert args to python */ |
| 172 |
va_end(argslist); |
| 173 |
if (args == NULL) /* args incref'd */ |
| 174 |
return -1; |
| 175 |
if (PP_DEBUG) /* debug this call? */ |
| 176 |
presult = PP_Debug_Function(object, args); /* run in pdb; incref'd */ |
| 177 |
else |
| 178 |
presult = PyObject_CallObject(object, args); /* run function; incref'd */ |
| 179 |
|
| 180 |
Py_DECREF(args); /* result may be None */ |
| 181 |
return PP_Convert_Result(presult, resfmt, cresult); /* convert result to C*/ |
| 182 |
} |
| 183 |
|
| 184 |
/***************************************************************************** |
| 185 |
* PYTHON EXCEPTION INFORMATION ACCESS |
| 186 |
* fetch Python-related error info (type, value); |
| 187 |
* after an API call returns an exception indicator, call |
| 188 |
* PP_Fetch_Error_Text, then get text from the 3 char[]'s; |
| 189 |
* note: calling PyErr_Fetch() clears/erases the current |
| 190 |
* exception in the Python system, as does PyErr_Print(), |
| 191 |
* so you should call one of these, one time, per exception: |
| 192 |
* caveats: not thread-specific since saves data in globals, |
| 193 |
* and only exports traceback object (the exception type and |
| 194 |
* data are converted to text strings and discarded); the |
| 195 |
* PyErr_Print() built-in also does a bit more on syntax errors, |
| 196 |
* and sends its text to sys.stderr: in principle, we could |
| 197 |
* assign stderr to a StringIO object and call PyErr_Print, but |
| 198 |
* the code here makes the 3 exception components more distinct; |
| 199 |
*****************************************************************************/ |
| 200 |
|
| 201 |
#define MAX 2024 |
| 202 |
/* |
| 203 |
FC_OS_LINUX: This is dangerous. How about PY_EXCEPT_MAX? |
| 204 |
*/ |
| 205 |
|
| 206 |
/* exception text is here after PP_Fetch_Error_Text call */ |
| 207 |
char PP_last_error_type[MAX]; /* exception name text */ |
| 208 |
char PP_last_error_info[MAX]; /* exception data text */ |
| 209 |
char PP_last_error_trace[MAX]; /* exception traceback text */ |
| 210 |
|
| 211 |
PyObject *PP_last_traceback = NULL; /* saved exception traceback object */ |
| 212 |
PyObject *PP_PyDict_Object = NULL; /* saved exception dictionary object */ |
| 213 |
PyObject *PP_last_exception_type = NULL; /* saved exception python type */ |
| 214 |
|
| 215 |
|
| 216 |
void PP_Fetch_Error_Text() |
| 217 |
{ |
| 218 |
|
| 219 |
char *tempstr = NULL; |
| 220 |
PyObject *errobj = NULL, *errdata = NULL, *errtraceback = NULL, *pystring = NULL, *pydict = NULL; |
| 221 |
|
| 222 |
/* get latest python exception information */ |
| 223 |
/* this also clears the current exception */ |
| 224 |
|
| 225 |
PyErr_Fetch(&errobj, &errdata, &errtraceback); /* all 3 incref'd */ |
| 226 |
|
| 227 |
|
| 228 |
/* convert type and data to strings */ |
| 229 |
/* calls str() on both to stringify */ |
| 230 |
|
| 231 |
pystring = NULL; |
| 232 |
if (errobj != NULL && |
| 233 |
(pystring = PyObject_Str(errobj)) != NULL && /* str(errobj) */ |
| 234 |
(PyUnicode_Check(pystring)) ) /* str() increfs */ |
| 235 |
{ |
| 236 |
strncpy(PP_last_error_type, PyUnicode_AsUTF8(pystring), MAX); /*Py->C*/ |
| 237 |
PP_last_error_type[MAX-1] = '\0'; |
| 238 |
} |
| 239 |
else |
| 240 |
{ |
| 241 |
PP_last_error_type[0] = '\0'; |
| 242 |
} |
| 243 |
|
| 244 |
Py_XDECREF(pystring); |
| 245 |
|
| 246 |
pystring = NULL; |
| 247 |
pydict = NULL; |
| 248 |
if (errdata != NULL && |
| 249 |
(PyDict_Check(errdata)) ) /* str() increfs */ |
| 250 |
{ |
| 251 |
// PyDict_GetItemString returns a borrowed reference |
| 252 |
// so we must make sure not to decrement the reference |
| 253 |
PyObject* value = PyDict_GetItemString(errdata,"swhat"); |
| 254 |
|
| 255 |
if (value!=NULL) { |
| 256 |
strncpy(PP_last_error_info, PyUnicode_AsUTF8(value), MAX); |
| 257 |
PP_last_error_info[MAX-1] = '\0'; |
| 258 |
} |
| 259 |
|
| 260 |
pydict = errdata; |
| 261 |
Py_INCREF(pydict); |
| 262 |
} |
| 263 |
else if (errdata != NULL && |
| 264 |
(pystring = PyObject_Str(errdata)) != NULL && /* str(): increfs */ |
| 265 |
(PyUnicode_Check(pystring)) ) |
| 266 |
{ |
| 267 |
strncpy(PP_last_error_info, PyUnicode_AsUTF8(pystring), MAX); /*Py->C*/ |
| 268 |
PP_last_error_info[MAX-1] = '\0'; |
| 269 |
} |
| 270 |
else |
| 271 |
strcpy(PP_last_error_info, "<unknown exception data>"); |
| 272 |
|
| 273 |
Py_XDECREF(pystring); |
| 274 |
|
| 275 |
/* convert traceback to string */ |
| 276 |
/* print text to a StringIO.StringIO() internal file object, then */ |
| 277 |
/* fetch by calling object's .getvalue() method (see lib manual); */ |
| 278 |
|
| 279 |
pystring = NULL; |
| 280 |
if (errtraceback != NULL && |
| 281 |
(PP_Run_Function("io", "StringIO", "O", &pystring, "()") == 0) && |
| 282 |
|
| 283 |
(PyTraceBack_Print(errtraceback, pystring) == 0) && |
| 284 |
(PP_Run_Method(pystring, "getvalue", "s", &tempstr, "()") == 0) ) |
| 285 |
{ |
| 286 |
strncpy(PP_last_error_trace, tempstr, MAX); |
| 287 |
PP_last_error_trace[MAX-1] = '\0'; |
| 288 |
free(tempstr); /* it's a strdup */ |
| 289 |
} |
| 290 |
else { |
| 291 |
PyFrameObject* frame = PyEval_GetFrame(); |
| 292 |
if(!frame) |
| 293 |
return; |
| 294 |
int line = PyFrame_GetLineNumber(frame); |
| 295 |
#if PY_VERSION_HEX < 0x030b0000 |
| 296 |
const char *file = PyUnicode_AsUTF8(frame->f_code->co_filename); |
| 297 |
#else |
| 298 |
PyCodeObject* code = PyFrame_GetCode(frame); |
| 299 |
const char *file = PyUnicode_AsUTF8(code->co_filename); |
| 300 |
Py_DECREF(code); |
| 301 |
#endif |
| 302 |
#ifdef FC_OS_WIN32 |
| 303 |
const char *_f = strstr(file, "\\src\\"); |
| 304 |
#else |
| 305 |
const char *_f = strstr(file, "/src/"); |
| 306 |
#endif |
| 307 |
snprintf(PP_last_error_trace,sizeof(PP_last_error_trace),"%s(%d)",(_f?_f+5:file),line); |
| 308 |
} |
| 309 |
Py_XDECREF(pystring); |
| 310 |
|
| 311 |
Py_XDECREF(PP_last_exception_type); |
| 312 |
if(errobj) { |
| 313 |
PP_last_exception_type = errobj; |
| 314 |
Py_INCREF(errobj); |
| 315 |
}else |
| 316 |
PP_last_exception_type = 0; |
| 317 |
Py_XDECREF(errobj); |
| 318 |
Py_XDECREF(errdata); /* this function owns all 3 objects */ |
| 319 |
Py_XDECREF(PP_last_traceback); /* they've been NULL'd out in Python */ |
| 320 |
Py_XDECREF(PP_PyDict_Object); |
| 321 |
PP_last_traceback = errtraceback; /* save/export raw traceback object */ |
| 322 |
PP_PyDict_Object = pydict; |
| 323 |
} |
| 324 |
|
| 325 |
|
| 326 |
/***************************************************************************** |
| 327 |
* GET/SET MODULE-LEVEL (GLOBAL) PYTHON VARIABLES BY NAME |
| 328 |
* handles module (re)loading, input/output conversions; |
| 329 |
* useful for passing data to/from codestrings (no args or return |
| 330 |
* val)--load module, set inputs, run codestring, get outputs; |
| 331 |
* subtle thing: Python "s" output conversion code sets a C char* to |
| 332 |
* the text in the middle of a Python string object, which may be |
| 333 |
* returned to the heap if decref'd--this api copies the text to a new |
| 334 |
* char array (with strdup) that the caller must free() when possible, |
| 335 |
* rather than assuming the caller can and will copy the result out; |
| 336 |
* could postpone the decref till next api call, but that's too subtle; |
| 337 |
*****************************************************************************/ |
| 338 |
|
| 339 |
|
| 340 |
int |
| 341 |
PP_Convert_Result(PyObject *presult, const char *resFormat, void *resTarget) |
| 342 |
{ |
| 343 |
if (presult == NULL) /* error when run: fail */ |
| 344 |
return -1; |
| 345 |
else |
| 346 |
if (resTarget == NULL) { /* passed target=NULL: ignore result */ |
| 347 |
Py_DECREF(presult); /* procedures and stmts return None */ |
| 348 |
return 0; |
| 349 |
} |
| 350 |
if (! PyArg_Parse(presult, resFormat, resTarget)) { /* convert Python->C */ |
| 351 |
Py_DECREF(presult); /* need not be tuple */ |
| 352 |
return -1; /* error in convert */ |
| 353 |
} |
| 354 |
if (strcmp(resFormat, "O") != 0) { /* free object unless exported */ |
| 355 |
if (strcmp(resFormat, "s") == 0) { /* copy string: caller owns it */ |
| 356 |
char **target = (char**) resTarget; |
| 357 |
#if defined (__GNUC__) |
| 358 |
*target = strdup(*target); |
| 359 |
#else |
| 360 |
*target = _strdup(*target); |
| 361 |
#endif |
| 362 |
} |
| 363 |
Py_DECREF(presult); |
| 364 |
} |
| 365 |
return 0; /* returns 0=success, -1=failure */ |
| 366 |
/* if 0: C result in *resTarget */ |
| 367 |
} /* caller must decref if fmt="O" */ |
| 368 |
/* caller must free() if fmt="s" */ |
| 369 |
|
| 370 |
int |
| 371 |
PP_Get_Global(const char *modname, const char *varname, const char *resfmt, void *cresult) |
| 372 |
{ |
| 373 |
PyObject *var = NULL; /* "x = modname.varname" */ |
| 374 |
var = PP_Load_Attribute(modname, varname); /* var is incref'd */ |
| 375 |
return PP_Convert_Result(var, resfmt, cresult); /* convert var to C form */ |
| 376 |
} |
| 377 |
|
| 378 |
|
| 379 |
int |
| 380 |
PP_Set_Global(const char *modname, const char *varname, const char *valfmt, ... /* cval(s) */) |
| 381 |
{ |
| 382 |
int result = 0; |
| 383 |
PyObject *module = NULL, *val = NULL; /* "modname.varname = val" */ |
| 384 |
va_list cvals; |
| 385 |
va_start(cvals, valfmt); /* C args after valfmt */ |
| 386 |
|
| 387 |
module = PP_Load_Module(modname); /* get/load module */ |
| 388 |
if (module == NULL) { |
| 389 |
va_end(cvals); |
| 390 |
return -1; |
| 391 |
} |
| 392 |
val = Py_VaBuildValue(valfmt, cvals); /* convert input to Python */ |
| 393 |
va_end(cvals); |
| 394 |
if (val == NULL) |
| 395 |
return -1; |
| 396 |
result = PyObject_SetAttrString(module, varname, val); |
| 397 |
Py_DECREF(val); /* set global module var */ |
| 398 |
return result; /* decref val: var owns it */ |
| 399 |
} /* 0=success, varname set */ |
| 400 |
|
| 401 |
|
| 402 |
/***************************************************************************** |
| 403 |
* MODULE INTERFACE |
| 404 |
* make/import/reload a python module by name |
| 405 |
* Note that Make_Dummy_Module could be implemented to keep a table |
| 406 |
* of generated dictionaries to be used as namespaces, rather than |
| 407 |
* using low level tools to create and mark real modules; this |
| 408 |
* approach would require extra logic to manage and use the table; |
| 409 |
* see basic example of using dictionaries for string namespaces; |
| 410 |
*****************************************************************************/ |
| 411 |
|
| 412 |
|
| 413 |
int PP_RELOAD = 0; /* reload modules dynamically? */ |
| 414 |
int PP_DEBUG = 0; /* debug embedded code with pdb? */ |
| 415 |
|
| 416 |
|
| 417 |
const char *PP_Init(const char *modname) { |
| 418 |
Py_Initialize(); /* init python if needed */ |
| 419 |
if (modname) |
| 420 |
return modname; |
| 421 |
/* we assume here that the caller frees allocated memory */ |
| 422 |
return "__main__"; |
| 423 |
} |
| 424 |
|
| 425 |
|
| 426 |
int |
| 427 |
PP_Make_Dummy_Module(const char *modname) /* namespace for strings, if no file */ |
| 428 |
{ /* instead of sharing __main__ for all */ |
| 429 |
PyObject *module = NULL, *dict = NULL; /* note: __main__ is created in py_init */ |
| 430 |
Py_Initialize(); |
| 431 |
module = PyImport_AddModule(modname); /* fetch or make, no load */ |
| 432 |
if (module == NULL) /* module not incref'd */ |
| 433 |
return -1; |
| 434 |
/* module.__dict__ */ |
| 435 |
dict = PyModule_GetDict(module); /* ['__dummy__'] = None */ |
| 436 |
PyDict_SetItemString(dict, "__dummy__", Py_None); |
| 437 |
PyDict_SetItemString(dict, "__builtins__", PyEval_GetBuiltins()); |
| 438 |
return 0; |
| 439 |
} |
| 440 |
|
| 441 |
|
| 442 |
PyObject * /* returns module object named modname */ |
| 443 |
PP_Load_Module(const char *modname) /* modname can be "package.module" form */ |
| 444 |
{ /* reload just resets C extension mods */ |
| 445 |
/* |
| 446 |
* 4 cases: |
| 447 |
* - module "__main__" has no file, and not prebuilt: fetch or make |
| 448 |
* - dummy modules have no files: don't try to reload them |
| 449 |
* - reload=on and already loaded (on sys.modules): "reload()" before use |
| 450 |
* - not loaded yet, or loaded but reload=off: "import" to fetch or load |
| 451 |
*/ |
| 452 |
|
| 453 |
PyObject *module = NULL, *sysmods = NULL; |
| 454 |
modname = PP_Init(modname); /* default to __main__ */ |
| 455 |
|
| 456 |
if (strcmp(modname, "__main__") == 0) /* main: no file */ |
| 457 |
return PyImport_AddModule(modname); /* not increfd */ |
| 458 |
|
| 459 |
sysmods = PyImport_GetModuleDict(); /* get sys.modules dict */ |
| 460 |
module = PyDict_GetItemString(sysmods, modname); /* mod in sys.modules? */ |
| 461 |
|
| 462 |
if (module != NULL && /* dummy: no file */ |
| 463 |
PyModule_Check(module) && |
| 464 |
PyDict_GetItemString(PyModule_GetDict(module), "__dummy__")) { |
| 465 |
return module; /* not increfd */ |
| 466 |
} |
| 467 |
if (PP_RELOAD && module != NULL && PyModule_Check(module)) { |
| 468 |
module = PyImport_ReloadModule(module); /* reload file,run code */ |
| 469 |
Py_XDECREF(module); /* still on sys.modules */ |
| 470 |
return module; /* not increfd */ |
| 471 |
} |
| 472 |
module = PyImport_ImportModule(modname); /* fetch or load module */ |
| 473 |
Py_XDECREF(module); /* still on sys.modules */ |
| 474 |
return module; /* not increfd */ |
| 475 |
} |
| 476 |
|
| 477 |
|
| 478 |
PyObject * |
| 479 |
PP_Load_Attribute(const char *modname, const char *attrname) |
| 480 |
{ |
| 481 |
PyObject *module = NULL; /* fetch "module.attr" */ |
| 482 |
modname = PP_Init(modname); /* use before PyEval_CallObject */ |
| 483 |
module = PP_Load_Module(modname); /* not incref'd, may reload */ |
| 484 |
if (module == NULL) |
| 485 |
return NULL; |
| 486 |
return PyObject_GetAttrString(module, attrname); /* func, class, var,.. */ |
| 487 |
} /* caller must xdecref */ |
| 488 |
|
| 489 |
|
| 490 |
/* extra ops */ |
| 491 |
int |
| 492 |
PP_Run_Command_Line(const char *prompt) |
| 493 |
{ |
| 494 |
int res = 0; /* interact with python, in "__main__" */ |
| 495 |
Py_Initialize(); /* in the program's "stdio" window */ |
| 496 |
if (prompt != NULL) |
| 497 |
#if defined (FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) |
| 498 |
printf("[%s <Use Ctrl-D (i.e. EOF) to exit.>]\n", prompt); |
| 499 |
#elif defined (FC_OS_WIN32) |
| 500 |
printf("[%s <Use Ctrl-Z plus Return to exit.>]\n", prompt); |
| 501 |
#endif |
| 502 |
res = PyRun_InteractiveLoop(stdin, "<stdin>"); |
| 503 |
return res; |
| 504 |
} |
| 505 |
|
| 506 |
/***************************************************************************** |
| 507 |
* RUN EMBEDDED CODE-STRINGS |
| 508 |
* handles debugging, module (re)loading, namespaces, output conversions; |
| 509 |
* pbd.runeval returns a value: "eval(expr + '\n', globals, locals)"; |
| 510 |
* pdb.run is just a statement: "exec cmd + '\n' in globals, locals" |
| 511 |
* New tools: precompiling strings to bytecode, running bytecode; |
| 512 |
*****************************************************************************/ |
| 513 |
|
| 514 |
|
| 515 |
|
| 516 |
int |
| 517 |
PP_Run_Codestr(PPStringModes mode, const char *code, /* expr or stmt string */ |
| 518 |
const char *modname, /* loads module if needed */ |
| 519 |
const char *resfmt, void *cresult) /* converts expr result to C */ |
| 520 |
{ |
| 521 |
/* run a string of Python code */ |
| 522 |
int parse_mode = 0; /* "eval(code, d, d)", or */ |
| 523 |
PyObject *module = NULL, *dict = NULL, *presult = NULL; /* "exec code in d, d" */ |
| 524 |
|
| 525 |
module = PP_Load_Module(modname); /* get module, init python */ |
| 526 |
if (module == NULL) /* not incref'd */ |
| 527 |
return -1; |
| 528 |
dict = PyModule_GetDict(module); /* get dict namespace */ |
| 529 |
if (dict == NULL) /* not incref'd */ |
| 530 |
return -1; |
| 531 |
|
| 532 |
parse_mode = (mode == PP_EXPRESSION ? Py_eval_input : Py_file_input); |
| 533 |
if (PP_DEBUG) |
| 534 |
presult = PP_Debug_Codestr(mode, code, dict); /* run in pdb */ |
| 535 |
else |
| 536 |
presult = PyRun_String(code, parse_mode, dict, dict); /* eval direct */ |
| 537 |
/* increfs res */ |
| 538 |
if (mode == PP_STATEMENT) { |
| 539 |
int result = (presult == NULL? -1 : 0); /* stmt: 'None' */ |
| 540 |
Py_XDECREF(presult); /* ignore result */ |
| 541 |
return result; |
| 542 |
} |
| 543 |
return PP_Convert_Result(presult, resfmt, cresult); /* expr val to C */ |
| 544 |
} |
| 545 |
|
| 546 |
|
| 547 |
PyObject * |
| 548 |
PP_Compile_Codestr(PPStringModes mode, /* precompile string to bytecode */ |
| 549 |
const char *codestr) /* pass result to PP_Run_Bytecode */ |
| 550 |
{ |
| 551 |
int start = 0; |
| 552 |
Py_Initialize(); |
| 553 |
switch (mode) { |
| 554 |
case PP_STATEMENT: |
| 555 |
start = Py_file_input; break; |
| 556 |
case PP_EXPRESSION: |
| 557 |
start = Py_eval_input; break; |
| 558 |
default: |
| 559 |
start = Py_single_input; /* prints expr results */ |
| 560 |
} |
| 561 |
return Py_CompileString(codestr, "<PP_Compile_Codestr>", start); |
| 562 |
} |
| 563 |
|
| 564 |
|
| 565 |
int |
| 566 |
PP_Run_Bytecode(PyObject *codeobj, /* run compiled bytecode object */ |
| 567 |
const char *modname, /* in named module's namespace */ |
| 568 |
const char *resfmt, void *restarget) |
| 569 |
{ |
| 570 |
PyObject *presult = NULL, *module = NULL, *dict = NULL; |
| 571 |
|
| 572 |
if (! PyCode_Check(codeobj)) /* make sure it's bytecode */ |
| 573 |
return -1; |
| 574 |
module = PP_Load_Module(modname); /* get module, init python */ |
| 575 |
if (module == NULL) /* not incref'd */ |
| 576 |
return -1; |
| 577 |
dict = PyModule_GetDict(module); /* get dict namespace */ |
| 578 |
if (dict == NULL) /* not incref'd */ |
| 579 |
return -1; |
| 580 |
if (PP_DEBUG) |
| 581 |
presult = PP_Debug_Bytecode(codeobj, dict); /* run in pdb */ |
| 582 |
else |
| 583 |
presult = PyEval_EvalCode((PyObject*)codeobj, dict, dict); |
| 584 |
return PP_Convert_Result(presult, resfmt, restarget); /* expr val to C */ |
| 585 |
} |
| 586 |
|
| 587 |
|
| 588 |
/************************************************************************** |
| 589 |
* subtle things: |
| 590 |
* 1) pdb.run and pdb.runeval both accept either a string or a |
| 591 |
* compiled code object, just because they call the built in exec and |
| 592 |
* eval(), which allow either form; further, eval() works on code |
| 593 |
* objects compiled as either expressions or statements, but returns |
| 594 |
* None as the result of statements, so we don't need to distinguish |
| 595 |
* between expressions and statements here again for bytecode (we |
| 596 |
* did when compiling); the equivalents in Python code: |
| 597 |
* >>> a = 1 |
| 598 |
* >>> s = compile('x = 1', '', 'exec') |
| 599 |
* >>> e = compile('a + 1', '', 'eval') |
| 600 |
* >>> print eval(e) |
| 601 |
* 2 |
| 602 |
* >>> print eval(s) |
| 603 |
* None |
| 604 |
* on the other hand, we can't blindly use pdb.runeval when dealing |
| 605 |
* with uncompiled strings, because eval() fails on statement strings; |
| 606 |
* |
| 607 |
* 2) in 1.5, if you debug a string or bytecode object in a module's |
| 608 |
* namespace where you've already debugged once, you may see a bogus |
| 609 |
* return value on entry which is left over from a prior debug; this |
| 610 |
* is because pdb leaves a '__return__' attribute in the module's |
| 611 |
* dictionary, which may be a pdb bug, but we work around it here by |
| 612 |
* manually deleting __return__ if present before starting pdb again; |
| 613 |
* only happens for strings--function namespaces aren't persistent; |
| 614 |
**************************************************************************/ |
| 615 |
|
| 616 |
|
| 617 |
static void fixPdbRetval(PyObject *moddict) |
| 618 |
{ if (PyDict_DelItemString(moddict, "__return__")) PyErr_Clear(); } |
| 619 |
|
| 620 |
|
| 621 |
PyObject * |
| 622 |
PP_Debug_Codestr(PPStringModes mode, const char *codestring, PyObject *moddict) |
| 623 |
{ |
| 624 |
int res = 0; |
| 625 |
PyObject *presult = NULL; |
| 626 |
const char *pdbname = (mode == PP_EXPRESSION ? "runeval" : "run"); |
| 627 |
fixPdbRetval(moddict); |
| 628 |
/* pass code to a pbd.py function */ |
| 629 |
res = PP_Run_Function( /* "pdb.run(stmt, gdict, ldict)" */ |
| 630 |
"pdb", pdbname, /* "pdb.runeval(expr, gdict, ldict)" */ |
| 631 |
"O", &presult, |
| 632 |
"(sOO)", codestring, moddict, moddict); |
| 633 |
return (res != 0) ? NULL : presult; /* return null or increfd object */ |
| 634 |
} |
| 635 |
|
| 636 |
|
| 637 |
PyObject * |
| 638 |
PP_Debug_Bytecode(PyObject *codeobject, PyObject *moddict) |
| 639 |
{ |
| 640 |
int res = 0; |
| 641 |
PyObject *presult = NULL; |
| 642 |
fixPdbRetval(moddict); |
| 643 |
res = PP_Run_Function( /* "pdb.runeval(codeobj, gdict, ldict)" */ |
| 644 |
"pdb", "runeval", /* accepts string|code, code=stmt|expr */ |
| 645 |
"O", &presult, |
| 646 |
"(OOO)", codeobject, moddict, moddict); |
| 647 |
return (res != 0) ? NULL : presult; /* null if error in run_function */ |
| 648 |
} |
| 649 |
// NOLINTEND |
| 650 |
// clang-format on |