473,786 Members | 2,660 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Forgetful Interpreter

Having seen the number of lost souls asking questions about embedding
Python in the archives of this group, I hesitate to add myself to
their number, but I've hit a problem I can't quite get my head around.

I have a simple C program that embeds a python interpreter to execute
python commands and return stdout, and to a point everything works as
intended. The problem that each command seems to be executed in its
own context and knows nothing of what's come before. So if enter
"print 2+2", I get back "4", but if I enter "a=2+2" then enter "print
a", I get back the error, "a is undefined." My guess is that this has
something to calling PyRun_SimpleStr ing inside of a child process, but
I can't get much further than this.

Any assistance is appreciated.

thanks

-Bill

//call this once at the beginning to initialize
void * nyptho_doinit(t _gogo* x, short flag)
{
Py_Initialize() ;
char capture_stdout[] ="import sys,
StringIO\n\sys. stderr=sys._cap ture=StringIO.S tringIO()\n";
int rc = PyRun_SimpleStr ing(capture_std out);
return x;
}

//this executes the command
FILE * nyptho_exec(t_g ogo* x, char * cmd, short bflag, short fflag)
{
int pfd[2],i,z=0;
pid_t pid;
FILE *fp;
extern int errno;

if (pipe(pfd) < 0)
return(NULL); // errno set by pipe()

if ( (pid = fork()) < 0)
return(NULL); // errno set by fork()

else if (pid == 0) // child
{
close(pfd[0]);

// close all descriptors in childpid[]
if (x->childpid[0] > 0)
close(0);

PyRun_SimpleStr ing(cmd);

//PyRun_SimpleStr ing("import sys");
PyObject* sysmod = PyImport_Import Module("sys");
PyObject* capobj =
PyObject_GetAtt rString(sysmod, "_capture") ;
PyObject* strres =
PyObject_CallMe thod(capobj,"ge tvalue",0);
char * dodo = PyString_AsStri ng(strres);
strcpy(globalBu f,dodo);

write(pfd[1], globalBuf, (long)strlen(gl obalBuf));
globalBuf[0]='\0';

_exit(127); //child exits
}
// parent
close(pfd[1]);

if ( (fp = fdopen(pfd[0], "r")) == NULL)
return(NULL);

x->childpid[fileno(fp)] = pid; // remember child pid for this
fd
return(fp);

}
Jul 18 '05 #1
3 1646
Bill Orcutt wrote:
Having seen the number of lost souls asking questions about
embedding Python in the archives of this group, I hesitate to add
myself to their number, but I've hit a problem I can't quite get
my head around.

I have a simple C program that embeds a python interpreter to
execute python commands and return stdout, and to a point
everything works as intended. The problem that each command seems
to be executed in its own context and knows nothing of what's come
before. So if enter "print 2+2", I get back "4", but if I enter
"a=2+2" then enter "print a", I get back the error, "a is
undefined." My guess is that this has something to calling
PyRun_SimpleStr ing inside of a child process, but I can't get much
further than this.


Take a look at Python-2.3.2/Demo/embed/demo.c in the Python source
code distribution for clues. That program calls
PyRun_SimpleStr ing() several times with the same context. If you
do not switch interpreters (thread state, whatever) or
re-initialize etc, then each call to PyRun_SimpleStr ing() should
have the same global variables etc.

Why are you calling fork()? Someone else will have to tell you
the consequences of doing that.

Dave

[snip]

--
Dave Kuhlman
http://www.rexx.com/~dkuhlman
dk******@rexx.c om
Jul 18 '05 #2
Thanks for your reply. I agree that PyRun_SimpleStr ing should be
running in the same context-- its worked that way for me in the past--
The only thing that's different this time is fork() and that's what
I'm hoping someone will tell me how to deal with, since I'm stuck with
it this time.

I'm updating the subject line to something more descriptive.

thanks

-Bill

Dave Kuhlman <dk******@rexx. com> wrote in message news:<bm******* *****@ID-139865.news.uni-berlin.de>...
Bill Orcutt wrote:
Having seen the number of lost souls asking questions about
embedding Python in the archives of this group, I hesitate to add
myself to their number, but I've hit a problem I can't quite get
my head around.

I have a simple C program that embeds a python interpreter to
execute python commands and return stdout, and to a point
everything works as intended. The problem that each command seems
to be executed in its own context and knows nothing of what's come
before. So if enter "print 2+2", I get back "4", but if I enter
"a=2+2" then enter "print a", I get back the error, "a is
undefined." My guess is that this has something to calling
PyRun_SimpleStr ing inside of a child process, but I can't get much
further than this.


Take a look at Python-2.3.2/Demo/embed/demo.c in the Python source
code distribution for clues. That program calls
PyRun_SimpleStr ing() several times with the same context. If you
do not switch interpreters (thread state, whatever) or
re-initialize etc, then each call to PyRun_SimpleStr ing() should
have the same global variables etc.

Why are you calling fork()? Someone else will have to tell you
the consequences of doing that.

Dave

[snip]

Jul 18 '05 #3
What you are doing won't work -- fork() behaves as though it makes a
copy of all the data in the current process's address spaces, so changes
in the child aren't mirrored in the parent.

Example C program:

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>

int i = 0;

void increment_i_in_ forked_subproce ss() {
pid_t pid = fork();
if (pid == -1) {
perror("fork"); exit(1);
}
if (pid == 0) {
i++;
printf("In subprocess %d, i=%d\n", getpid(), i);
exit(0);
}
wait(NULL);
printf("Subproc ess exited\n");
}

int main(void) {
int j;
for(j=0; j<10; j++) {
increment_i_in_ forked_subproce ss();
}
return 0;
}

$ gcc orcutt.c && ./a.out
In subprocess 16632, i=1
Subprocess exited
In subprocess 16633, i=1
Subprocess exited
In subprocess 16634, i=1
Subprocess exited
In subprocess 16635, i=1
Subprocess exited
In subprocess 16636, i=1
Subprocess exited
In subprocess 16637, i=1
Subprocess exited
In subprocess 16638, i=1
Subprocess exited
In subprocess 16639, i=1
Subprocess exited
In subprocess 16640, i=1
Subprocess exited
In subprocess 16641, i=1
Subprocess exited
Jul 18 '05 #4

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

Similar topics

12
2410
by: Anon | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello all I am a beginner teaching myself python, and I am enjoying it immensely :) As a language it is great, I real treat to study, I actually find it fun to study the language heh Anyways to the point of my post.....
1
2915
by: Donnie Leen | last post by:
I wrote a program embbed boost.python, each thread running a sub-interpreter, i made a module implement by boost.python, and i wish this module imported in each sub-interpreter, i find that the module could initialize only once, otherwise the boost.python will throw a exception said that something already registered; second conversion method ignored. So I try another way, initialize and import the module in one interpreter such as the main...
12
12285
by: Rex Eastbourne | last post by:
Hi, I'm interested in running a Python interpreter in Emacs. I have Python extensions for Emacs, and my python menu lists "C-c !" as the command to run the interpreter. Yet when I run it I get the message "Spawning Child Process: invalid argument." What do I need to do/download to fix this? I read in a post in this group from a while back where someone had the following lines in his .emacs file:
4
1989
by: Ian Giblin | last post by:
I am an experienced C programmer, learning C++ by writinging a mathematical toolkit in the framework of a script interpreter. I am posting here to ask for advice (or references) on the object design and implimentation. Currently I have a portable "ScriptSession" class which contains the mechanics of looping with a user prompt, parsing a sentence and handling syntax errors, etc., and I wan this to be a class I can use for any script...
12
1887
by: ozbear | last post by:
If one were writing a C interpreter, is there anything in the standard standard that requires the sizeof operator to yield the same value for two different variables of the same type? Let's assume that the interpreter does conform to the range values for, say, type int, but allocates storage for the variables based on their value. So, for two variables foo and bar int foo = 0; /* interpreter allocates two bytes */ int bar =...
6
5515
by: gr | last post by:
hi.. I must implement an interpreter in C programming language that will get the source code of a program in text file format and execute it. but i don't know C language enough to write this interpreter. so I need this interpreter code that is written with C language.(or it can be C++) I searched this codes in google and some websites, but codes which I found are useless.. if you can help me, you gladden me.
3
1569
by: Robin Becker | last post by:
As part of some django usage I need to get some ReportLab C extensions into a state where they can be safely used with mod_python. Unfortunately we have C code that seems incompatible with mod_python and I'm looking for ways to improve the situation. Basically the main things that are wrong are all privately cached copies of python variables. This sample code
40
2379
by: castironpi | last post by:
I'm curious about some of the details of the internals of the Python interpreter: I understand C from a hardware perspective. x= y+ 1; Move value from place y into a register Add 1 to the value in the register Move the addition's result to place x
5
21430
by: Erik Hahn | last post by:
I'm looking for a standalone Javascript interpreter like the ones of Perl and Python. Does such a thing exist for Linux? Thanks in advance. -Erik -- hackerkey://v4sw5hw2ln3pr5ck0ma2u7LwXm4l7Gi2e2t4b7Ken4/7a16s0r1p-5.62/-6.56g5OR
0
9655
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, 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...
0
9497
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
10169
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
9964
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...
1
7517
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
6749
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5398
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...
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
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...

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.