tags:

views:

45

answers:

3

Well i want to input a python function as an input in run time and execute that part of code 'n' no of times. For example using tkinter i create a textbox where the user writes the function and submits it , also mentioning how many times it wants to be executed. My program should be able to run that function as many times as mentioned by the user.

Ps: i did think of an alternative method where the user can write the program in a file and then i can simply execute it as python filename as a system cmd inside my python program , but i dont want it that way.

A: 

Would IPython do?

Doc: http://ipython.scipy.org/moin/Documentation

underdark
+1  A: 

Python provides number of ways to do this using function calls: - eval() - exec()

For your needs you should read about exec.

Piotr Duda
Just be very careful about the security -- you're basically allowing any user who has access to that input to execute any arbitrary code as the user who's executing the python program. Should be fine if it's just a single user environment, but if any part of the program needs administrative/root privileges or if that input goes to a server somewhere else to execute, you're just asking for trouble.
well basically the input function will be run over the cluster network. But for now i would limit to single system , since i am building a small prototype. but wat kind of security issues are you taking about ?
Rahul
Giving someone the ability to run in `exec` gives them pretty complete power over the machine. How would you feel if someone ran this code: `import os, os.pathfor root, dirs, files in os.walk('.'): for f in files: fullpath = os.path.join(root, f) os.remove(fullpath)`
hughdbrown
well its for my project .. so its more like a controlled demonstration. I am trying to create a map reduce framework
Rahul
A: 

That's what execfile() is for.

http://docs.python.org/library/functions.html#execfile

  1. Create a temporary file.

  2. Write the content of the textbox into the file.

  3. Close.

  4. Execfile.

  5. Delete when done.

S.Lott
well performance is also a constraint here , would creating and deleting a temp file increase the time of execution ?
Rahul
Yes. Microscopically. Try to measure it.
S.Lott