Hi
I spent the whole of yesterday trying the get the following C code to
execute
PyRun_String("d ef title();", Py_file_input, dict, dict);
PyRun_String("\ treturn 'Foo Bar'", Py_file_input, dict, dict);
PyRun_String("x = title()", Py_file_input, dict, dict);
PyObject * result = PyRun_String("p rint x", Py_file_input, dict, dict);
printf( "The result is %s\n", PyObject_AsStri ng( result );
Each line throws an error.
Could somebody tell what is wrong with the above code.
Here below is the output from my test app
Starting Test ......
The file "testtitle" is open for reading
The variable codeStrings contains
Line 0 def title()
Line 1 return "Foo Bar"
The variable scriptText contains
def title()
return "Foo Bar"
The variable tempList contains
Line 0 testtitle
Line 1 title
Module Name is testtitle
Function Name is title
The variable functionCode contains
def title()
return "Foo Bar"
Python initialized successfully
Module object successfully created
Dict object successfully created
Failed to create a Result object.
The title of the this task is <nil>
--
Best Regards
John 6 4217
John Dean wrote: Hi
I spent the whole of yesterday trying the get the following C code to execute
PyRun_String("d ef title();", Py_file_input, dict, dict);
^^^^^^^^^^^
Try using a colon here....
PyRun_String("\ treturn 'Foo Bar'", Py_file_input, dict, dict); PyRun_String("x = title()", Py_file_input, dict, dict); PyObject * result = PyRun_String("p rint x", Py_file_input, dict, dict); printf( "The result is %s\n", PyObject_AsStri ng( result );
Overall it seems to me that ther must be a better way to do such a thing -
even in C. AFAIK it supports multiline-stringliterals. Why don't you do
something like this:
script = "\
def foo():\n\
return 'FooBar'\n\
x = title()\n\
print x\n"
And then read that script line by line, feeding it to the parser. Or maybe
the parser even groks that string at once - don't know that.
Diez
John Dean wrote: PyRun_String("d ef title();", Py_file_input, dict, dict); PyRun_String("\ treturn 'Foo Bar'", Py_file_input, dict, dict); PyRun_String("x = title()", Py_file_input, dict, dict); PyObject * result = PyRun_String("p rint x", Py_file_input, dict, dict); printf( "The result is %s\n", PyObject_AsStri ng( result );
Each line throws an error.
Please don't paraphrase your code when asking questions such as this. The
code above doesn't even compile (unmatched parentheses) so any response
must be a guess as to which parts were wrong in your original code and
which errors you introduced just for the posting.
Each call to PyRun_String is independant. You seem to think you can call
the function with part of your source code and then continue with more of
the source in another call. You cannot.
Try concatenating the lines together to at least make complete statements.
Also make sure to handle the result from every call to PyRun_String: check
it for null, if it is null you should format and print the error message.
The following is your code rewritten as a working program. When you run it,
it will tell you about the syntax error in your Python code. Fix that and
you will see your program output.
#include <python.h>
void run() {
PyObject *dict = PyDict_New();
PyObject *result;
if (dict==NULL) {
PyErr_Print();
return;
}
result = PyRun_String("d ef title();\n\tret urn 'Foo Bar'\n",
Py_file_input, dict, dict);
if (result==NULL) {
PyErr_Print();
return;
} else {
Py_DECREF(resul t);
}
result = PyRun_String("x = title()", Py_file_input, dict, dict);
if (result==NULL) {
PyErr_Print();
return;
} else {
Py_DECREF(resul t);
}
result = PyRun_String("p rint x", Py_file_input, dict, dict);
if (result==NULL) {
PyErr_Print();
return;
} else {
PyObject *rString = PyObject_Str(re sult);
if (rString==NULL) {
Py_DECREF(resul t);
PyErr_Print();
return;
}
printf( "The result is %s\n", PyString_AsStri ng(rString));
Py_DECREF(rStri ng);
Py_DECREF(resul t);
}
}
int main(int argc, char **argv) {
Py_Initialize() ;
run();
}
Hi Duncan
Your version of the app works apart from this part
.....
.....
else {
PyObject *rString = PyObject_Str(re sult);
if (rString==NULL) {
Py_DECREF(resul t);
PyErr_Print();
return;
}
printf( "The result is %s\n", PyString_AsStri ng(rString));
Py_DECREF(rStri ng);
Py_DECREF(resul t);
}
}
The result of the printf state is: "The result is None"
result = PyRun_String("p rint x", Py_file_input, dict, dict);
The above line of code displays the value returned from the title()
function. My problem is I need to be able to cature the return value because
in the real application it will be displayed in a Process Log Widget. Also
the real scripts will be much longer.
I have not had a problem writing Python extensions, but when it comes to
embedded Python I just see how to get my code to work.
Any further help would be greatly appreciated
--
Best Regards
John
Hi
Duncan's example worked to a point. The line PyRun_String( "print x",
Py_file_input, dict, dict); print out the contents of x, but I don't want to
print x out. I want to be able to grab whateven the variable x contains so
that I can pass it on for further processing by the C++ application.
BTW this is only a test case. The real scripts are much bigger. I must say
the documentation is not of much help and there are no books or articles
covering embedding Python in any detail. What there is is very much out of
date.
--
Best Regards
John
John Dean wrote: Duncan's example worked to a point. The line PyRun_String( "print x", Py_file_input, dict, dict); print out the contents of x, but I don't want to print x out. I want to be able to grab whateven the variable x contains so that I can pass it on for further processing by the C++ application.
a better approach is to combine embedding and extending, and let the em-
bedded code use your extension to talk to your program.
if you want your program to access x, let the embedded script do
import myapp
myapp.write(x)
since you know how to extend Python, implementing write should be trivial.
if you insist on picking out variables from the embedded script, you can use
the same approach as when you want to pull out variables from code you've
exec'ed: run the code in a namespace dictionary, and extract the data from
the dictionary after you've run the code. i.e.
g = {}
exec code in g
x = g["x"]
becomes
PyObject *g, *x;
g = PyDict_New();
PyDict_SetItemS tring(g, "__builtins __", PyEval_GetBuilt ins());
PyRun_String(my code, Py_file_input, g, NULL);
x = PyDict_GetItemS tring(g, "x");
Py_DECREF(g);
(the SetItemString call is probably not needed in all cases)
BTW this is only a test case. The real scripts are much bigger. I must say the documentation is not of much help and there are no books or articles covering embedding Python in any detail. What there is is very much out of date.
well, I'm getting a bit tired of all this "if it's not published within the last
few weeks, it's out of date" nonsense that people keep using as an excuse
for procrastination . The Python C API is very stable, and the embedding
and extending basics haven't changed a bit in a decade.
and "no books" is also wrong; ORA's "Programmin g Python" spends some
40 pages on embedding only (including examples on how to extract stuff
from module namespaces). I'm pretty sure it's not the only one.
</F>
John Dean wrote: Hi Duncan
Your version of the app works apart from this part
.... ....
else { PyObject *rString = PyObject_Str(re sult); if (rString==NULL) { Py_DECREF(resul t); PyErr_Print(); return; }
printf( "The result is %s\n", PyString_AsStri ng(rString)); Py_DECREF(rStri ng); Py_DECREF(resul t); } }
The result of the printf state is: "The result is None"
Yes, what did you expect it to be? The result from executing the Python
code was the value None.
result = PyRun_String("p rint x", Py_file_input, dict, dict);
The above line of code displays the value returned from the title() function. My problem is I need to be able to cature the return value because in the real application it will be displayed in a Process Log Widget. Also the real scripts will be much longer.
I have not had a problem writing Python extensions, but when it comes to embedded Python I just see how to get my code to work.
Any further help would be greatly appreciated
If you want the value of x, then pick it out of the dictionary:
{
PyObject *x = PyDict_GetItemS tring(dict, "x");
PyObject *rString = PyObject_Str(x) ;
printf( "x is %s\n", PyString_AsStri ng(rString));
Py_DECREF(rStri ng);
Py_DECREF(x);
}
Py_DECREF(dict) ; // I forgot this one in my original code.
If you want to embed Python though you really should look at Pyrex. Using
Pyrex you can all but forget about the Python api, write a Pyrex function
which is callable directly from C: it calls the Python code and returns the
C values you want as a result. Also it will handle all the error checking
and reference counting automatically. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Kostatus |
last post by:
I have a virtual function in a base class, which is then overwritten by a
function of the same name in a publically derived class. When I call the
function using a pointer to the derived class (ClassB* b; b->func(); ) the
base-class function is called instead of the new function in the derived
class. All other similar functions (virtual in...
|
by: Peter Olcott |
last post by:
www.halting-problem.com
|
by: Ian Stanley |
last post by:
Hi,
Continuing my strcat segmentation fault posting-
I have a problem which occurs when appending two sting literals using
strcat.
I have tried to fix it by writing my own function that does the strcat
(mystract). Program below.
However this appears not to have fixed the problem and I don't know why it
shouldn't ?
Any further help as to...
|
by: Jon Davis |
last post by:
If I have a class with a virtual method, and a child class that overrides
the virtual method, and then I create an instance of the child class AS A
base class...
BaseClass bc = new ChildClass();
.... and then call the virtual method, why is it that the base class's method
is called instead of the overridden method? How do I fix this if I...
|
by: Ammar |
last post by:
Dear All,
I'm facing a small problem.
I have a portal web site, that contains articles, for each article, the end
user can send a comment about the article.
The problem is:
I the comment length is more that 1249 bytes, then the progress bar of the
browser will move too slow and then displaying that the page not found!!!!
If the message is...
| |
by: Dany |
last post by:
Our web service was working fine until we installed .net Framework 1.1 service pack 1. Uninstalling SP1 is not an option because our largest customer says service packs marked as "critical" by Microsoft must be installed on their servers.
Now german Umlaute (ä, ü, ö) and quotes are returned incorrectly in SOAP fault responses.
This can be...
|
by: Mike Collins |
last post by:
I cannot get the correct drop down list value from a drop down I have on my
web form. I get the initial value that was loaded in the list.
It was asked by someone else what the autopostback was set to...it is set to
false.
Can someone show me what I am doing wrong and tell me the correct way? Thank
you.
In the page load event, I am...
|
by: =?Utf-8?B?am8uZWw=?= |
last post by:
Hello All,
I am developing an Input Methop (IM) for PocketPC / Windows Mobile (PPC/WM).
On some
devices the IM will not start. The IM appears in the IM-List but when it is
selected from the list athe result is that the standard (QWERTY) keyboard
appears.
I found that many ( all?) ISV's who make IM's have customers reporting this...
|
by: sherifbk |
last post by:
Problem description
==============
- I have 4 clients and 1 server (SQL server)
- 3 clients are Monitoring console 1 client is operation console
- Monitoring console collects some data from the control unit and
store them into the Sql server
- The operation console then retrieve this data from the sql for
reporting and statistics...
|
by: AceKnocks |
last post by:
I am working on a framework design problem in which I have to design a C++ based framework capable of solving three puzzles for now but actually it should work with a general puzzle of any kind and I need your able help in this activity.
Objective -
In this activity you will design a framework capable of solving any puzzle of a specific type...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it. ...
| |
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...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
|
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...
|
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...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes...
|
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...
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |