By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,035 Members | 1,388 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,035 IT Pros & Developers. It's quick & easy.

HowTo exec every line of a file inside python program

P: n/a
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"
Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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
Jul 18 '05 #2

P: n/a
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.
Look up execfile under built-in functions is the docs.

-tim


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

Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.