>>> inp = 'x*x'
>>> func='def f(x): return ' + inp
>>> func
'def f(x): return x*x'
>>> exec func
>>> f(3)
9
Now you have f(x) defined as a regular function and you can plot it the same as a function you wrote in your code.
The user will have to use whatever variable name you expect. And this is a huge security hole, you shouldn't do it if you don't trust the users.
Kent
Ismael Garrido wrote:
Hello
I am trying to make a program that will plot functions. For that, I need to be able to get an input (the function to be plotted) and execute it. So, my question is, how do I use the input? I have found no way to convert the string to some kind of executable code.
I did research the problem. And found two things, first, an unsatisfactory solution from: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52217
The code there, by means I cannot understand at all, executes a string as code. To be usable I have to make my code a huge string. It is not very elegant.
The second possible solution I found was using eval, compile and/or exec. But I do not understand what do they do, or how to use them, for the matter.
Related to the program I intend to do, which design would you say is more intelligent: one that first calculates the whole function, stores it, and then plots it; or one that calculates-plots-calc.-plot, and so on?
Thanks for any information, and for your time. Ismael _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor