Mercurial > hg > pyloader
annotate pyloader/loader.py @ 2:6cb7696edc4d
add some more stuff for string loady type things and rearrange structure
author | Jeff Hammel <jhammel@mozilla.com> |
---|---|
date | Tue, 10 May 2011 09:28:40 -0700 |
parents | pyloader/__init__.py@47d9472e7754 |
children | 65d9a7c7ac63 |
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 |
11 def import_dotted_path(module): | |
12 path = module.split('.') | |
13 module = __import__(module) | |
14 for name in path[1:]: | |
15 module = getattr(module, name) | |
16 return module | |
17 | |
18 def load(string): | |
19 """loads a string and returns a python object""" | |
20 | |
21 try: | |
22 if ':' in string: | |
23 path, target = string.split(':', 1) | |
24 if os.path.isabs(path) and os.path.exists(path): | |
25 # path to file | |
1
47d9472e7754
add path of file directory when loading files
Jeff Hammel <jhammel@mozilla.com>
parents:
0
diff
changeset
|
26 sys.path.append(os.path.dirname(path)) |
0 | 27 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
|
28 sys.path.pop() |
0 | 29 else: |
30 module = import_dotted_path(path) | |
31 obj = module | |
32 while '.' in target: | |
33 attr, target = target.split('.', 1) | |
34 obj = getattr(obj, attr) | |
35 obj = getattr(obj, target) | |
36 return obj | |
37 else: | |
38 # module: dotted path | |
39 return import_dotted_path(string) | |
40 except: | |
41 print string | |
42 raise | |
43 | |
44 # TODO: entry points | |
45 | |
46 if __name__ == '__main__': | |
47 import sys | |
48 for i in sys.argv[1:]: | |
49 print load(i) |