Run python script inside python script

I have a script where I want to dynamically generate a python script - inside my main python script - store it as a string, and then, when necessary, execute this dynamically generated script from my main script.

Is this possible, if so, how?

thanks

+6
python
source share
6 answers
+6
source share

For script in file use exec

For script in line use eval

!!! But !!!

Before using strings passed from an external source, check them out! Otherwise, you will find it possible to execute arbitrary code from within your program, so the range will check your variables!

You will never want to ask a question:

"Excuse me, Mom, will you really call your son Robert"), DROP TABLE students - "?

If you do not understand the link - see this quick cartoon ...

http://xkcd.com/327/

but when you are EVAL, you are solely responsible for the instructions you evaluate.

+12
source share

An exec statement may be required: http://docs.python.org/release/2.5.2/ref/exec.html

+1
source share

If you want to execute the script in the context of the main script, you can check eval [ http://docs.python.org/py3k/library/functions.html#eval ]

+1
source share

Not sure how tricky this is, but it's not an exec function, what do you use if you need to execute Python code?

0
source share

There is a priority for what you are trying to do. The collections.namedtuple function creates a template string that is passed to exec to build a dynamically defined class.

0
source share

All Articles