MCPcopy Create free account
hub / github.com/Colvars/colvars / Tcl_python

Function Tcl_python

namd/src/ScriptTcl.C:372–456  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

370}
371
372int ScriptTcl::Tcl_python(ClientData, Tcl_Interp *interp, int argc, const char **argv) {
373 if ( argc < 2 ) {
374 Tcl_SetResult(interp,(char*)"args: script",TCL_VOLATILE);
375 return TCL_ERROR;
376 }
377 namd_python_initialize(interp);
378 PyObject *dict = PyModule_GetDict(PyImport_AddModule("__main__"));
379
380 const char *script = argv[1];
381 int token = Py_eval_input;
382
383 Tcl_DString scr;
384 Tcl_DStringInit(&scr);
385 if ( argc > 2 ) {
386 Tcl_DStringAppend(&scr,argv[1],-1);
387 for ( int i = 2; i < argc; ++i ) {
388 Tcl_DStringAppend(&scr," ",-1);
389 Tcl_DStringAppend(&scr,argv[i],-1);
390 }
391 script = Tcl_DStringValue(&scr);
392 } else {
393 while ( script[0] == ' ' || script[0] == '\t' ) ++script;
394 for ( int i=0; script[i]; ++i ) {
395 if ( script[i] == '\n' ) {
396 token = Py_file_input;
397 script = argv[1];
398 break;
399 }
400 }
401 }
402
403 PyObject *result = PyRun_String(script, token, dict, dict);
404 Tcl_ResetResult(interp); // Python may have called Tcl
405 Tcl_DStringFree(&scr);
406
407 if ( PyErr_Occurred() ) {
408 if ( result ) NAMD_bug("PyErr_Occurred indicates error but PyRun does not");
409 // PyErr_Print();
410 Tcl_AppendResult(interp, "error from python interpreter\n", NULL);
411 PyObject *type, *value, *traceback, *str;
412 PyErr_Fetch(&type, &value, &traceback);
413
414 if ( ! traceback ) {
415 traceback = Py_None;
416 Py_INCREF(Py_None);
417 }
418
419 PyObject *mod = PyImport_ImportModule("traceback");
420 if ( ! mod ) return TCL_ERROR;
421
422 PyObject *func = PyObject_GetAttrString(mod, "format_exception");
423 if ( ! func ) return TCL_ERROR;
424
425 // TODO understand why this call fails in Python3 in cases where the
426 // traceback is not None
427 PyObject *list = PyObject_CallFunctionObjArgs(func, type, value, traceback, NULL);
428 if ( ! list ) return TCL_ERROR;
429

Callers

nothing calls this directly

Calls 2

namd_python_initializeFunction · 0.85
python_tcl_convertFunction · 0.85

Tested by

no test coverage detected