[C++-sig] Renaming "<string>" filename for PyRun_String
David Faure
dfaure at klaralvdalens-datakonsult.se
Fri Jun 2 19:10:20 CEST 2006
Victor Nakoryakov <nail-mail at mail.ru> wrote:
> I use PyRun_String to run script stored in some file. I can't use
> PyRun_File because of different layouts of FILE struct in my project and
> in python lib. So once I get error I see something like:
>
> Traceback (most recent call last):
> File "<string>", line 14, in ?
> NameError: ...
>
> Is it possible somehow to rename "<string>" in this message to the real filename?
I just had the same problem, and I solved it by copying some code out of the pythonrun.c sources...
[This means it would be nice for the python developers to provide a PyRun_StringFileName().
Just like it would be nice to have a public function that calls tb_printinternal, parse_syntax_error, etc
in order to print out all the info about a parsing or runtime error just like python itself does.]
Anyway; this code does the job for me:
#include <node.h> // from python
// Copied from pythonrun.c
static PyObject *run_node(struct _node *n, const char *filename, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) {
PyCodeObject *co;
PyObject *v;
co = PyNode_CompileFlags(n, filename, flags);
PyNode_Free(n);
if (co == NULL)
return NULL;
v = PyEval_EvalCode(co, globals, locals);
Py_DECREF(co);
return v;
}
// This is missing from python: a PyRun_String that also takes a filename, to show in backtraces
static PyObject* MyPyRun_StringFileName(const char *str, const char* filename, int start, PyObject *globals, PyObject *locals) {
struct _node* n = PyParser_SimpleParseString(str, start);
if (!n) return 0;
return run_node( n, filename, globals, locals, 0 );
}
--
David Faure -- faure at kde.org, dfaure at klaralvdalens-datakonsult.se
KDE/KOffice developer, Qt consultancy projects
Klarälvdalens Datakonsult AB, Platform-independent software solutions
More information about the Cplusplus-sig
mailing list