473,398 Members | 2,812 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

better way of executing expression/statement in C?

Hi,

Given arbitrary Python source code input by the user, I want to get the
result of executing that source as an expression if it is an expression
and otherwise execute the source as a statement. Currently, I'm
accomplishing this as follows (in a category on NSString), but it seems
kludgy to rely on detecting a syntax error.

- (PyObject*)executePythonSourceWithGlobals:(PyObjec t*)globals
{
const char* source = [self UTF8String];
PyObject* result = PyRun_String(source, Py_eval_input, globals,
globals);
if (!result && PyErr_ExceptionMatches(PyExc_SyntaxError)) {
PyErr_Clear();
result = PyRun_String(source, Py_file_input, globals, globals);
}
return result;
}

How would you accomplish this? How does the interpreter do it?

Thank you.

David
AIM: pitulx
Jul 18 '05 #1
1 1896

This might be slightly less kludgy...I tested it by implementing a
crude input loop. Here is the output:

[rlratzel@triumph ~/exp] ./pyexec
a=3 RESULT: NULL b=4 RESULT: NULL a+b RESULT: 7 c=4 RESULT: NULL a+c RESULT: 7 import os RESULT: NULL Done.

Here is the code:

file: pyexec.c
--------
#include <Python.h>
#define INLEN 1024

/*
* get string rep of a Python obj
*/
const char* getPyObjStringRepr( PyObject* pyObj ) {
if( pyObj == NULL ) {
return "NULL";
} else {
return PyString_AsString( PyObject_Str( pyObj ) );
}
}
/*
* print the results of evaluating Python expressions and statements
*/
int main( int argc, char** argv ) {

PyObject* mainModObj;
PyObject* mainDictObj;
PyObject* returnObj;
PyObject* resultObj;
char userInput[INLEN];

Py_Initialize();

/*
* create a different display hook to set a result var
* rather than print to stdout and set __builtin__._
*/
PyRun_SimpleString( "import sys, __main__" );
PyRun_SimpleString( "def my_displayhook(o): __main__.__result=o" );
PyRun_SimpleString( "sys.displayhook=my_displayhook" );

/*
* get the __main__ symbol table for evaluating within the top-most
* scope and retrieving the result
*/
mainModObj = PyImport_AddModule( "__main__" );
if( mainModObj == NULL ) {
return -1;
}
mainDictObj = PyModule_GetDict( mainModObj );

/*
* start an eval loop...only print 2 arrows since we are
* not really trying to be Python
*/
printf( ">> " );

/*
* start the loop
*/
while( fgets( userInput, INLEN, stdin ) != NULL ) {

/*
* run a string from the command line like the interactive interp
* does, handling both expressions and statements
*/
returnObj = PyRun_String( userInput, Py_single_input,
mainDictObj, mainDictObj );

if( returnObj == NULL ) {
PyErr_Print();
return -1;
}

/*
* get the result as set by the displayhook and print it out
*/
resultObj = PyDict_GetItemString( mainDictObj, "__result" );

printf( "RESULT: %s\n", getPyObjStringRepr( resultObj ) );

Py_DECREF( returnObj );
if( Py_FlushLine() ) {
PyErr_Clear();
}

/*
* if a result was set, delete it so statements which dont return
* a value dont return a prior set value
*/
if( resultObj != NULL ) {
PyRun_SimpleString( "del __main__.__result" );
}

printf( ">> " );
}

printf( "Done.\n" );
return 0;
}
--------

Not sure if that is exactly what you were looking for, but it does
allow one to execute statements and expressions and process the result
(if any).

-Rick Ratzel
David Faden wrote: Hi,

Given arbitrary Python source code input by the user, I want to get the
result of executing that source as an expression if it is an expression
and otherwise execute the source as a statement. Currently, I'm
accomplishing this as follows (in a category on NSString), but it seems
kludgy to rely on detecting a syntax error.

- (PyObject*)executePythonSourceWithGlobals:(PyObjec t*)globals
{
const char* source = [self UTF8String];
PyObject* result = PyRun_String(source, Py_eval_input, globals,
globals);
if (!result && PyErr_ExceptionMatches(PyExc_SyntaxError)) {
PyErr_Clear();
result = PyRun_String(source, Py_file_input, globals, globals);
}
return result;
}

How would you accomplish this? How does the interpreter do it?

Thank you.

David
AIM: pitulx

Jul 18 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Michael | last post by:
Hi, I'm fairly new at Python, and have the following code that works but isn't very concise, is there a better way of writing it?? It seems much more lengthy than python code i have read..... :-)...
12
by: Me | last post by:
Hi, I would like learn from people with experience in C++, which of the following styles of way to construct "get/set" member functions would be the best in terms of usability, speed, et cetera. ...
52
by: Darklight | last post by:
Question: Write a function named sumarrays() that accepts two arrays that are the same size. The function should add each element in the array together and place the values in the thrid array. ...
14
by: John Temples | last post by:
Given this code: extern volatile unsigned char v; int main(void) { v; return 0; }
10
by: Mike | last post by:
I know this sounds strange but I am at a loss. I am calling a simple funtion that opens a connection to a SQL Server 2000 database and executes an Insert Statement. private void...
2
by: Divakar | last post by:
Hi, How can we find which SQL statement is executing when "list application show detail" shows "UOW Executing" against an application. This topic was touched upon earlier by one of the member....
1
by: lovecreatesbea... | last post by:
---quoting--- Annex C (informative) Sequence points 1 The following are the sequence points described in 5.1.2.3: - The end of a full expression: an initializer (6.7.8); the expression in an...
20
by: TimeHorse | last post by:
I would like to gauge interest in the following proposal: Problem: Assignment statements cannot be used as expressions. Performing a list of mutually exclusive checks that require data...
18
by: dspfun | last post by:
Hi! The words "expression" and "statement" are often used in C99 and C- textbooks, however, I am not sure of the clear defintion of these words with respect to C. Can somebody provide a sharp...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
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,...
0
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...
0
jinu1996
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...
0
agi2029
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,...
0
isladogs
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.