embedding interactive python interpreter
Mark Hammond
mhammond at skippinet.com.au
Mon Mar 28 20:36:34 EDT 2011
On 28/03/2011 2:06 PM, Eric Frederich wrote:
> I'm not sure that I know how to run this function in such a way that
> it gives me an interactive session.
> I passed in stdin as the first parameter and NULL as the second and
> I'd get seg faults when running exit() or even imnport sys.
>
> I don't want to pass a file. I want to run some C code, start an
> interactive session, then run some more C code once the session is
> over, but I cannot find a way to start an interactive Python session
> within C that won't exit pre-maturely before I have a chance to run my
> cleanup code in C.
Instead of calling Py_Main, arrange for the following code to be executed:
import code
try:
code.interact()
except SystemExit:
pass
print "Done!"
If you save that as a script and run it, you will see that when you call
quit() or use Ctrl+D, the "Done!" is printed (so the exception is
caught) and things will return normally (albeit without any return code
that may have been specified in the SystemExit exception). If you
arrange to call that code in your app (either by importing it as a
module of even by calling PyRun_SimpleString) things should work as you
need.
HTH,
Mark
More information about the Python-list
mailing list