Hi, May you please help in using Py_CompileString & PyEval_EvalCode to parse+compile an expression at startup & evaluate that multiple times at runtime. I want to use this in C++ program as below.
Here, the expression contains the variables like size, vol, ADV, etc. The values of these variables keep on changing for every user input in C++ program. The problem I am facing is that, I am not able to pass these values from C++ code to Python code, when calling PyEval_EvalCode. Can you please guide me about my following queries: 1) how can I make these variables in C++ to be available to Python compiled code at runtime? 2) my this code got compiled but when running, I got an error from Py_CompileString, as below. Why is it so? File "<string>", line 1 if ( (size < 1000) & (vol < (0.001 * ADV)) & (prod=="Stock")): print "OK" ^ SyntaxError: invalid syntax But when I executed the same code in python process, it worked fine. 3) Is this correct use of Py_CompileString, PyEval_EvalCode & Py_BuildValue functions? Please help, guide. Many thanks in advance. Regards, Ganesh //----------------------------------------------------- #include "Python.h" #include "compile.h" #include "eval.h" #include "object.h" #include <stdio.h> typedef struct { long size; long ADV; long vol; char prod[128]; } OrderValues, *pOrderValues; main() { Py_SetProgramName("MyPyEval"); Py_Initialize(); PyRun_SimpleString("import sys\n"); /** Expression to parse in Python syntax: if ( (size < 1000) & (vol < (0.001 * ADV)) & (prod=="Stock")) : print "OK" else print "NOK" **/ char szExpr[1024]; memset(szExpr,'\0',sizeof(szExpr)); sprintf(szExpr," if ( (size < 1000) & (vol < (0.001 * ADV)) & (prod==\"Stock\")): print \"OK\" \nelse: print \"NOK\" \n"); // Parse & compile this expression at startup & store the code object PyObject* co = Py_CompileString(szExpr,"<string>",Py_eval_input); if(pyco == NULL){ Py_Finalize(); exit(0); } PyCodeObject *pyCo = (PyCodeObject *)co; // Expression parsed & compiled ok, evaluate it multiple times PyObject *glb; glb = PyDict_New(); PyDict_SetItemString(glb, "__builtins__", PyEval_GetBuiltins()); while(1){ // These values change at runtime as per user input // Here only one set of values are shown for simplicity OrderValues ordval; ordval.size = 100; ordval.ADV = 100000; ordval.vol = 1000; memset(ordval.prod,'\0',sizeof(ordval.prod)); sprintf(ordval.prod,"Stock"); PyObject* vals = Py_BuildValue("(llls)",pVals->size,pVals->vol,pVals->ADV,pVals->prod); PyEval_EvalCode(pyCo,glb,vals); } Py_Finalize(); } //----------------------------------------------------- ============================================================================== Please access the attached hyperlink for an important electronic communications disclaimer: http://www.credit-suisse.com/legal/en/disclaimer_email_ib.html ============================================================================== -- http://mail.python.org/mailman/listinfo/python-list