Mercurial > hg > pyloader
annotate pyloader/loader.py @ 3:65d9a7c7ac63
other misc improvements
author | Jeff Hammel <jhammel@mozilla.com> |
---|---|
date | Tue, 10 May 2011 10:26:19 -0700 |
parents | 6cb7696edc4d |
children | 58eed691dca7 |
rev | line source |
---|---|
0 | 1 #!/usr/bin/env python |
2 | |
3 """ | |
4 load modules and their attributes from a string | |
5 """ | |
6 | |
7 import imp | |
8 import os | |
1
47d9472e7754
add path of file directory when loading files
Jeff Hammel <jhammel@mozilla.com>
parents:
0
diff
changeset
|
9 import sys |
0 | 10 |
3 | 11 __all__ = ['import_dotted_path', 'load'] |
12 | |
0 | 13 def import_dotted_path(module): |
14 path = module.split('.') | |
15 module = __import__(module) | |
16 for name in path[1:]: | |
17 module = getattr(module, name) | |
18 return module | |
19 | |
20 def load(string): | |
21 """loads a string and returns a python object""" | |
22 | |
23 try: | |
24 if ':' in string: | |
25 path, target = string.split(':', 1) | |
26 if os.path.isabs(path) and os.path.exists(path): | |
27 # path to file | |
1
47d9472e7754
add path of file directory when loading files
Jeff Hammel <jhammel@mozilla.com>
parents:
0
diff
changeset
|
28 sys.path.append(os.path.dirname(path)) |
0 | 29 module = imp.load_source(path, path) |
1
47d9472e7754
add path of file directory when loading files
Jeff Hammel <jhammel@mozilla.com>
parents:
0
diff
changeset
|
30 sys.path.pop() |
0 | 31 else: |
32 module = import_dotted_path(path) | |
33 obj = module | |
34 while '.' in target: | |
35 attr, target = target.split('.', 1) | |
36 obj = getattr(obj, attr) | |
37 obj = getattr(obj, target) | |
38 return obj | |
39 else: | |
40 # module: dotted path | |
41 return import_dotted_path(string) | |
42 except: | |
43 print string | |
44 raise | |
45 | |
46 # TODO: entry points | |
47 | |
48 if __name__ == '__main__': | |
49 import sys | |
50 for i in sys.argv[1:]: | |
51 print load(i) |