for my current task I have a Python interpreter embedded in a C++ program.
There are several ways through which the user can interact with this interpreter, typing code into it, and possibly also def-fining functions.
I need to be able to look into all defined functions, find one given its name and (here comes the hard part) read whatever code it currently contains.
I looked into the API and there is a PyCodeObject class, but it is subject to change at any time and I do not want to start using code that might just change the next time the user upgrades Python. Is there any documented and portable-across-versions way to read the code into a Python function just given its name?
Thanks for any help you'll be willing to provide on this
✆ 408.974.5572 | ✉ egranata@.com
On Jul 15, 2011, at 11:59 PM, Campbell Barton <ideasman42(a)gmail.com> wrote:
> Hi Enrico,
> Officially, I think what you want to do isn't really supported by python.
> - What if the python function is loaded from a pyc with no source code?
> - What if the function is defined in a string which is executed but
> does not correspond to a valid __file__ you can open and inspect.
Which is exactly the scenario I envision, unfortunately.
> In practice you can probably manage it if make a few assumptions.
> You can access these attributes (or their C values directly):
However these are not going to help me if the function data comes from standard input instead of from a file
> Personally I'd not worry about the PyCodeObject changing (though
> without more details on what you do its hard to say).
> Or you could import the 'inspect' module via the C api and call its
> getsource() function, however 'inspect' just makes a guess too and
> isn't guaranteed to give the correct result, this at least gets around
> changes in PyCodeObject but assumes a full python installation.
I guess this is not viable either, still thanks a lot for your helpful hints.
> capi-sig mailing list
I've built Python for the iPhone app store (not jailbreak),
Like embedding Python in another app, it uses PyRun_SimpleString()
to execute commands entered by the user. For evaluating expressions, it uses
PyEval_EvalCode() with the dictionary from the __main__ module.
My problem is that future division ("from __future__ import division") works
within scripts executed by import or execfile() but not when entered
interactively in the interpreter like this:
>>> from __future__ import division
When you do this, you get classic (integer) division, but if you enter it as
follows, you get future (float) division.
>>> from __future__ import division;a=2/3
It appears that the CO_FUTURE_DIVISION compiler flag is not being retained
in the interpreter so that later commands get compiled without that flag.
I found a hint in
I don't see that PyRun_SimpleStringFlags returns the flags it uses. I guess
I could watch for the user to enter the import command and set the flags on
every subsequent call but seems really brittle to me.