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.

1
  • this solution may work for you. Just create a dictionary of user defined functions by using exex input() in some_dict. stackoverflow.com/a/6098736/2368836 Commented Aug 16, 2014 at 23:52

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

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

For your needs you should read about exec.

4 Comments

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 ?
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)
well its for my project .. so its more like a controlled demonstration. I am trying to create a map reduce framework
0

Would IPython do?

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.