473,806 Members | 2,321 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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*)exec utePythonSource WithGlobals:(Py Object*)globals
{
const char* source = [self UTF8String];
PyObject* result = PyRun_String(so urce, Py_eval_input, globals,
globals);
if (!result && PyErr_Exception Matches(PyExc_S yntaxError)) {
PyErr_Clear();
result = PyRun_String(so urce, 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 1917

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

[rlratzel@triump h ~/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* getPyObjStringR epr( PyObject* pyObj ) {
if( pyObj == NULL ) {
return "NULL";
} else {
return PyString_AsStri ng( 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_SimpleStr ing( "import sys, __main__" );
PyRun_SimpleStr ing( "def my_displayhook( o): __main__.__resu lt=o" );
PyRun_SimpleStr ing( "sys.displayhoo k=my_displayhoo k" );

/*
* get the __main__ symbol table for evaluating within the top-most
* scope and retrieving the result
*/
mainModObj = PyImport_AddMod ule( "__main__" );
if( mainModObj == NULL ) {
return -1;
}
mainDictObj = PyModule_GetDic t( 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_GetItemS tring( mainDictObj, "__result" );

printf( "RESULT: %s\n", getPyObjStringR epr( 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_SimpleStr ing( "del __main__.__resu lt" );
}

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*)exec utePythonSource WithGlobals:(Py Object*)globals
{
const char* source = [self UTF8String];
PyObject* result = PyRun_String(so urce, Py_eval_input, globals,
globals);
if (!result && PyErr_Exception Matches(PyExc_S yntaxError)) {
PyErr_Clear();
result = PyRun_String(so urce, 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
1674
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..... :-) (takes a C++ block and extracts the namespaces from it) def ExtractNamespaces(data): print("Extracting Namespaces")
12
5762
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. The following class with be used as an example: class MyClass { public: // member function would go here. private: int data_;
52
2326
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. Which answer is the better practice; /*EX9.C*/ #include<stdio.h> #define MAX 5
14
2088
by: John Temples | last post by:
Given this code: extern volatile unsigned char v; int main(void) { v; return 0; }
10
3405
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 AddMinimunWageStipen(string payrollid,double amount) { System.Data.SqlClient.SqlConnection cn = null; System.Data.SqlClient.SqlCommand cm = null;
2
5231
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. That time responses were to use SNAPSHOT Monitor and a tool called db2top which is still under development. I have tried "get snapshot for application applid <appid>" with UOW
1
2893
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 expression statement (6.8.3); ... ---quoting ends--- What does a full expression exactly mean?
20
2146
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 processing can cause excessive tabification. For example, consider the following python snipet...
18
7980
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 defintion of "expression" and "statement"? What is the difference between an expression and a statement?
0
9597
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,...
0
10618
Oralloy
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10366
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 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...
0
10110
tracyyun
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...
0
9187
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, 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...
1
7649
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5546
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...
0
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4329
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 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.