run all scripts in sub-directory as subroutines?

G

guthrie

I want to have a program which will form a list of all *.py scripts in
a sub-directory, and then call some standard messages on them. So I
can add a new data source modularly by just dropping a new file into
the sources directory with the appropriate methods in it.

For example:

path = sys.path[0]
print "Starting Directory:: " + path

getDir=path + "\Sources" # point to directory of data
sources
for name in os.listdir(getDir): # run collection from each source
src = imp.load_source("data",getDir,open(getDir+"\\"+name, 'rb'))
src.getData()
src.doGraph()

This works fine, but in the sub-modules the sys.path appropriately
returns the same as from the parent, I want them to know their own
file names. How?? I can pass it to them, but wondered if there is a
more self-sufficient way for a module to know from where it was
invoked.
 
R

ryles

This works fine, but in the sub-modules the sys.path appropriately
returns the same as from the parent, I want them to know their own
file names. How?? I can pass it to them, but wondered if there is a
more self-sufficient way for a module to know from where it was
invoked.

Instead of sys.path, you may be interested in the __file__ attribute
will give you a module's filename:

http://docs.python.org/reference/simple_stmts.html#index-1031

You could also be more explicit in matching *.py files in your
subdirectory by using glob:

http://docs.python.org/library/glob.html
 
T

Tobiah

This works fine, but in the sub-modules the sys.path appropriately
returns the same as from the parent, I want them to know their own file
names. How?? I can pass it to them, but wondered if there is a more
self-sufficient way for a module to know from where it was invoked.

I like the idea of passing the information to the module.
Probably by setting a global variable into it.
 
D

Dave Angel

Tobiah said:
I like the idea of passing the information to the module.
Probably by setting a global variable into it.
As ryles pointed out in this thread, over a month ago, that's already
there. The system loader creates a global variable __file__ with the
full path to the module. So any module can see exactly where it was
loaded from.
 

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
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top