HowTo exec every line of a file inside python program

Peter Otten __peter__ at
Wed Feb 11 16:49:53 CET 2004

Joe Richett wrote:

> Hi all,
> I have a python program and I have some "user defined" command stored in
> a separate text file. Is there a builtin command with which I can load
> the "user defined"-file and execute every command line by line, e.g.
> #
> #
> def a(i):
>    print "here we are #", i
> if __name__ == "__main__":
>    for i in range(10):
>      a(i)
>      <execute everything from FILE.PY>
> ------------------------------------------------------
> #
> #
> print "here we are in the user defined file"

import user_defined_file

will do it (once) assuming the file is named and is in
the python path, e. g. in the current directory. However, it is better to
wrap the code in into a function to make exceution
independent from import:

import user_defined_file
# more code

Please read Python's excellent tutorial - it's a good starting point and has
some info on how to organize your code, too.


More information about the Python-list mailing list