在有egrep的平臺:
from subprocess import Popen, PIPE
from re import search
def get_classes(directory):
job = Popen(['egrep', '-ir', '--include=*.py', 'class ', str(directory), ], stdout=PIPE)
fileout, fileerr = job.communicate()
if fileerr:
raise Exception(fileerr)
while directory[-1] == '/':
directory = directory[:-1]
found = []
for line in fileout.split('\n'):
match = search('^([^:]+).py:\s*class\s*(\S+)\s*\((\S+)\):', line)
if match:
pypath = match.group(1).replace(directory, '').replace('/', '.')[1:]
cls = match.group(2)
parents = filter(lambda x: x.strip, match.group(3).split())
found.append((pypath, cls, parents,))
return found
爲get_classes('.')
,egrep的返回是這樣的:
./helpers/action.py:class Action(object):
./helpers/get_classes.py: job = Popen(['egrep', '-ir', '--include=*.py', 'class ', str(directory), ], stdout=PIPE) # this is the get_classes script; not a valid result
./helpers/options.py:class Option(object):
被轉換成路徑,類名的元組和直系祖先:
[('helpers.action', 'Action', ['object']), ('helpers.options', 'Option', ['object'])]
如果你只是想要的路徑,這是[item[0] for item in get_classes('.')]
。
啊,'__import__'函數看起來非常有用,謝謝你。 – Noldorin 2010-07-05 09:25:11
不是所有的成員都必須是類。 – mtnpaul 2011-11-10 21:01:35