HowTo exec every line of a file inside python program

Peter Otten __peter__ at web.de
Wed Feb 11 10:49:53 EST 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.
> 
> #
> # MAIN PROGRAM
> #
> 
> def a(i):
>    print "here we are #", i
> 
> if __name__ == "__main__":
>    for i in range(10):
>      a(i)
>      <execute everything from FILE.PY>
> 
> ------------------------------------------------------
> 
> #
> # USER DEFINED FILE
> #
> print "here we are in the user defined file"

import user_defined_file

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

import user_defined_file
# more code
user_defined_file.myfunc() 

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

Peter



More information about the Python-list mailing list