我是这样做的:import os
import sys
all_modules = {} #keeps track of the module names
def discoverModules():
''' Populates a dictionary holding every module name in the directory tree that this file is run '''
global all_modules
for dirname, dirnames, filenames in os.walk('.'):
# Advanced usage:
# editing the 'dirnames' list will stop os.walk() from recursing into there.
if '.git' in dirnames:
# don't go into any .git directories.
dirnames.remove('.git')
# save path to all subdirectories in the sys.path so we can easily access them:
for subdirname in dirnames:
name = os.path.join(dirname, subdirname) # complete directory path
sys.path.append(name) # add every entry to the sys.path for easy import
# save path to all filenames:
for filename in filenames:
# we want to save all the .py modules, but nothing else:
if '.py' in filename and '.pyc' not in filename and '__init__' not in filename:
moduleName = '' #this will hold the final module name
# If on Mac or Linux system:
if str(os.name) == 'posix':
for element in dirname.split('\/'): # for each folder in the traversal
if element is not '.': # the first element is always a '.', so remove it
moduleName += element + '.' # add a '.' between each folder
# If on windoze system:
elif str(os.name) == 'nt':
for element in dirname.split('\\'): # for each folder in the traversal
if element is not '.': # the first element is always a '.', so remove it
moduleName += element + '.' # add a '.' between each folder
# Important to use rstrip, rather than strip. If you use strip, it will remove '.', 'p', and 'y' instead of just '.py'
moduleName += filename.rstrip('.py') # finally, add the filename of the module to the name, minus the '.py' extension
all_modules[str(filename.rstrip('.py'))] = moduleName # add complete module name to the list of modules
print 'Discovering Modules...Complete!'
print 'Discovered ' + str(len(all_modules)) + ' Modules.'