473,396 Members | 1,766 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,396 software developers and data experts.

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_SimpleString 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._capture=StringIO.String IO()\n";
int rc = PyRun_SimpleString(capture_stdout);
return x;
}

//this executes the command
FILE * nyptho_exec(t_gogo* 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_SimpleString(cmd);

//PyRun_SimpleString("import sys");
PyObject* sysmod = PyImport_ImportModule("sys");
PyObject* capobj =
PyObject_GetAttrString(sysmod,"_capture");
PyObject* strres =
PyObject_CallMethod(capobj,"getvalue",0);
char * dodo = PyString_AsString(strres);
strcpy(globalBuf,dodo);

write(pfd[1], globalBuf, (long)strlen(globalBuf));
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 1628
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_SimpleString 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_SimpleString() several times with the same context. If you
do not switch interpreters (thread state, whatever) or
re-initialize etc, then each call to PyRun_SimpleString() 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.com
Jul 18 '05 #2
Thanks for your reply. I agree that PyRun_SimpleString 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_SimpleString 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_SimpleString() several times with the same context. If you
do not switch interpreters (thread state, whatever) or
re-initialize etc, then each call to PyRun_SimpleString() 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_subprocess() {
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("Subprocess exited\n");
}

int main(void) {
int j;
for(j=0; j<10; j++) {
increment_i_in_forked_subprocess();
}
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
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...
1
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...
12
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...
4
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...
12
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...
6
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...
3
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...
40
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...
5
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 --...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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,...
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
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...

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.