I am new to Python. I would like to use Python for the specialized purpose of dynamic expressions parsing & evaluation in my C++ application.
I would like to encapsulate the expressions to be evaluated in Python function & compile that function at runtime, somewhat as below.
Expression to eval put in Python function
def isSizeSmall(siz e,vol,ADV,prod) :
if ( (size < 1000) & (vol < (0.001 * ADV)) & (prod=="Stock") ): print "OK"; return 10
else: print "NOK"; return 11
Then, I want to evaluate the PyObject returned by Py_CompileStrin g multiple times in my program using the user input as the variables to the above function.
This I tried using two different approaches - 1) PyEval_evalCode , & 2) PyObject_CallOb ject.
1) When using PyEval_evalCode : The function call to PyEval_evalCode was ok, but it did not return any output.
2) Whereas, when I used this object with PyObject_CallOb ject, it failed with error as given below.
Any help will be great. Many thanks in advance for your help.
Warm Regards,
Ganesh
//*************** *************** *************** **//
Output of my test program:
Expression to eval =
"def isSizeSmall(siz e,vol,ADV,prod) :
if ( (size < 1000) & (vol < (0.001 * ADV)) & (prod=="Stock") ): print "OK"; return 10
else: print "NOK"; return 11"
str compiled fine with stdin & Py_file_input, calling PyEval_EvalCode
None ok [0] size [-1]
str compiled fine with stdin & Py_file_input, calling PyFunction_New & then PyObject_CallOb ject
Getting PyFunction_New
Calling PyObject_CallOb ject
func is callable TypeError: ?() takes no arguments (4 given)
My test program having both above approaches is as below: -
main(int argc, char **argv)
-
{
-
/* Pass argv[0] to the Python interpreter */
-
Py_SetProgramName(argv[0]);
-
/* Initialize the Python interpreter. Required. */
-
Py_Initialize();
-
PyRun_SimpleString("import sys\n");
-
-
char szExpr[2048];
-
memset(szExpr,'\0',sizeof(szExpr));
-
sprintf(szExpr,"def isSizeSmall(size,vol,ADV,prod):\n if ( (size < 1000) & (vol < (0.001 * ADV)) & (prod==\"Stock\")): print \"OK\"; return 10\n else: print \"NOK\"; return 11\n\n\n");
-
-
printf("Expression to eval = \n[%s]\n",szExpr);
-
-
OrderValues ordval;
-
ordval.size = 100;
-
ordval.ADV = 100000;
-
ordval.vol = 1000;
-
memset(ordval.prod,'\0',sizeof(ordval.prod));
-
sprintf(ordval.prod,"Stock");
-
-
-
PyObject *glb, *loc;
-
-
glb = PyDict_New();
-
PyDict_SetItemString(glb, "__builtins__", PyEval_GetBuiltins());
-
-
loc = PyDict_New();
-
-
PyObject* tuple = PyTuple_New(4);
-
PyObject* val = 0;
-
-
val = PyInt_FromLong(ordval.size);
-
PyTuple_SetItem(tuple,0,val);
-
PyDict_SetItemString(loc,"size",val);
-
-
val = PyInt_FromLong(ordval.vol);
-
PyTuple_SetItem(tuple,1,val);
-
PyDict_SetItemString(loc,"vol",val);
-
-
val = PyInt_FromLong(ordval.ADV);
-
PyTuple_SetItem(tuple,2,val);
-
PyDict_SetItemString(loc,"ADV",val);
-
-
val = PyString_FromString(ordval.prod);
-
PyTuple_SetItem(tuple,3,val);
-
PyDict_SetItemString(loc,"prod",val);
-
-
-
/*** with string & Py_file_input ***/
-
PyObject* result = NULL;
-
result = Py_CompileString(szExpr,"<string>", Py_file_input);
-
if(result!=NULL && !PyErr_Occurred()){
-
printf("str compiled fine with stdin & Py_file_input, calling PyEval_EvalCode\n");
-
-
PyCodeObject *pyCo = (PyCodeObject *)result;
-
PyObject* evalret = NULL;
-
evalret = PyEval_EvalCode(pyCo,glb,loc);
-
if(!evalret || PyErr_Occurred())
-
PyErr_Print();
-
else
-
printf("ok [%d] size [%d]\n",PyObject_Print(evalret,stdout,0),PyObject_Size(evalret));
-
-
// Try to get function obj of this...
-
printf("Getting PyFunction_New\n");
-
PyObject* func = PyFunction_New(result,glb);
-
if(!func || PyErr_Occurred()){
-
printf("Failed to get Function..\n");
-
PyErr_Print();
-
} else {
-
printf("Calling PyObject_CallObject\n");
-
if(PyCallable_Check(func))
-
printf("func is callable\n");
-
PyObject* ret = PyObject_CallObject(func, tuple);
-
//PyObject* ret = PyObject_CallObject(func, NULL);
-
if(!ret || PyErr_Occurred())
-
PyErr_Print();
-
else
-
printf("PyObject_CallObject evaluated..\n");
-
}
-
} else {
-
printf("Py_CompileString-1 returned NULL\n");
-
PyErr_Print();
-
}
-
exit(100);
-
}
0 2307 Sign in to post your reply or Sign up for a free account.
Similar topics |
by: mike420 |
last post by:
THE GOOD:
1. pickle
2. simplicity and uniformity
3. big library (bigger would be even better)
THE BAD:
|
by: Andrew Dalke |
last post by:
Is there an author index for the new version of the
Python cookbook? As a contributor I got my comp version
delivered today and my ego wanted some gratification.
I couldn't find my entries.
Andrew
dalke@dalkescientific.com
|
by: Russell |
last post by:
I want my code to be Python 3000 compliant, and hear
that lambda is being eliminated. The problem is that I
want to partially bind an existing function with a value
"foo" that isn't known until run-time:
someobject.newfunc = lambda x: f(foo, x)
The reason a nested function doesn't work for this is
that it is, well, dynamic. I don't know how many times
or with what foo's this will be done.
|
by: Gerald |
last post by:
Hi ,Im a BSc4 Maths/Computer Science student.Unfortunately my
curriculum did not include Python programming yet I see many vacancies
for Python developers.I studied programming Pascal,C++ and Delphi.So I
need to catch up quickly and master Python programming.How do you
suggest that I achieve this goal?Is python platform independent?What
is the best way?And how long would it take before I can develop
applications using python?Can you...
|
by: Mr.SpOOn |
last post by:
Hi,
I need a structure to represent a set of integers. I also need to
perform on this set some basic set operations, such as adding or
removing elements, joining with other sets and checking for the
presence of specific elements.
I think that using Python sets would be the best choice, but I also
need integers to be ordered inside the set and I've just found out
that, instead, Python sets are unordered collections.
| |
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |