HowTo exec every line of a file inside python program

J

Joe Richett

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"
 
P

Peter Otten

Joe said:
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
 
T

Tim Hochberg

Joe said:
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.

Look up execfile under built-in functions is the docs.

-tim
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,178
Messages
2,570,955
Members
47,509
Latest member
Jack116

Latest Threads

Top