[Tutor] Re: parsing?
Bill Bell
bill-bell@bill-bell.hamilton.on.ca
Thu, 28 Jun 2001 16:07:53 -0400
Ingo <seedseven@home.nl> wrote, in part:
> I'm tying to make something that can read some values and functions
> from a file and then use these to create a parametric surface in
> triangles to be rendered by POV-Ray. The triangle generation isn't the
> problem, but reading the functions into the program.
>
> If I have a line read from a textfile that says:
>
> u=2
>
> how do I manage to make a value u=2 available to the program, that
> read the textfile, so it can do some calculations with it?
>
> The same, but now for a function:
>
> Function Fx(u,v,R)=R*sin(u)*cos(v)
>
> How do I make the above available in the program as if the below was
> part of it?
>
> def Fx (u,v,R):
> x=R*sin(u)*cos(v)
> return x
Ingo,
You can use the Python 'exec' statement to handle at least part of
this problem.
For example,
>>> import math
>>> strFx = "def Fx (u,v,R): return R*math.sin(u)*math.cos(v)"
>>> exec strFx
>>> exec "u=1.57"
>>> Fx(u,3.14,5)
-4.9999920732988814
You could just as easily read the Python statements from a file
and arrange to make their results available in the current
namespace using this technique. The harder part would have to do
with translating the usual mathematical notation into Python.
However, if you're able to allow that that would be unnecessary
then you could just input the functions and other items that you
need in Python syntax.
I notice that there a Python constructs related to 'exec' that are
probably useful in this context.
Bill