How can I run precompiled code objects?
howard at eegsoftware.com
howard at eegsoftware.com
Fri Jul 13 14:29:47 EDT 2001
On Fri, 13 Jul 2001 13:20:57 +0200, "Alex Martelli"
<aleaxit at yahoo.com> wrote:
.....
>> Can anyone tell me how to use the so called "code objects" in Python, for
>> example the ones created via
>>
>> PyObject* Py_CompileString(char *str, char *filename, int start)
>>
........
>
>A "code block" is not suitable for eval(), so exec it will
>have to be, if you're working in Python as you said at the
>start. If you're working in C as you say now, the C API
>function you have to call is PyEval_EvalCode. It takes 3
>arguments -- a code object, then two dictionaries to use as
>local and global namespaces -- the last arg can be 0, but
>not the 2nd one.
>
.......
>
>Alex
>
>
>
So...I cut out the code sample (see below), located the extra includes
I needed (compile.h and eval.h) and tried it.
When I run my old method (PyRun_SimpleString), my script evaluates and
runs (Tkinter+PMW stuff) but I get an empty Tk window in addition to
my expected window.
When I run the PyEval_EvalCode method, it returns as though there was
not error but nothing (neither window) appears. The result from
PyEval_EvalCode appears to be Py_None but is not null.
Any Ideas????
Here is the code sample (I had to read the file into memory because of
the (apparently) know PyRun_File bug).
int
pyrunfile(void)
{
char *buf,*p;
long size=0;
int len,ans;
FILE *fp;
PyObject *ptype,*pvalue,*ptrace;
fp=fopen("stages.py","r");
if (fp)
{
buf=(char *)malloc(80000);
if (!buf)
return -1;
p=buf;
while (size < 80000 && !feof(fp))
{
p=fgets(p,1000,fp);
if (!p)
continue;
len=strlen(p);
size += len;
p= &p[len];
}
fclose(fp);
#if 1
ans=PyRun_SimpleString(buf);
if (ans == -1)
{
PyErr_Fetch (&ptype, &pvalue, &ptrace);
}
free(buf);
return 1;
#else
PyObject *globals, *code, *result;
/* prepare an innocuous 'globals' dictionary */
globals = PyDict_New();
PyDict_SetItemString(globals, "__builtins__",
PyEval_GetBuiltins());
/* compile your string of statements into a code object */
code = Py_CompileString(buf, "stages.py", Py_file_input);
if(!code)
{
PyErr_Print();
free(buf);
return 0;
}
free(buf);
/* execute the compiled statement */
result = PyEval_EvalCode((PyCodeObject *)code, globals, 0);
Py_DECREF(code);
if(!result)
{
PyErr_Print();
return 0;
}
else
{
Py_DECREF(result);
return 1;
}
#endif
}
Howard Lightstone
EEGSoftware
howard at eegsoftware.com
More information about the Python-list
mailing list