1

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.

Rahul
  • 11,129
  • 17
  • 63
  • 76
  • this solution may work for you. Just create a dictionary of user defined functions by using exex input() in some_dict. http://stackoverflow.com/a/6098736/2368836 – rocktheartsm4l Aug 16 '14 at 23:52

3 Answers3

2

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

For your needs you should read about exec.

Piotr Duda
  • 1,767
  • 11
  • 12
  • 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. – user470379 Oct 20 '10 at 19:13
  • 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 Oct 20 '10 at 19:21
  • 1
    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.path for root, dirs, files in os.walk('.'): for f in files: fullpath = os.path.join(root, f) os.remove(fullpath) ` – hughdbrown Oct 20 '10 at 19:30
  • well its for my project .. so its more like a controlled demonstration. I am trying to create a map reduce framework – Rahul Oct 22 '10 at 13:42
2

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
  • 384,516
  • 81
  • 508
  • 779
0

Would IPython do?

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

underdark
  • 1,146
  • 7
  • 22