Mercurial > hg > pyloader
annotate pyloader/loader.py @ 83:58eed691dca7
debugging
author | Jeff Hammel <jhammel@mozilla.com> |
---|---|
date | Mon, 11 Nov 2013 19:18:58 -0800 |
parents | 65d9a7c7ac63 |
children | 36f5d31c3ed6 |
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('.') | |
83 | 15 try: |
16 module = __import__(module) | |
17 except: | |
18 sys.stderr.write("pyloader: Error importing %s for dotted path %s\n" % (module, path)) | |
19 raise | |
20 | |
0 | 21 for name in path[1:]: |
22 module = getattr(module, name) | |
23 return module | |
24 | |
25 def load(string): | |
26 """loads a string and returns a python object""" | |
27 | |
28 try: | |
29 if ':' in string: | |
30 path, target = string.split(':', 1) | |
31 if os.path.isabs(path) and os.path.exists(path): | |
32 # path to file | |
1
47d9472e7754
add path of file directory when loading files
Jeff Hammel <jhammel@mozilla.com>
parents:
0
diff
changeset
|
33 sys.path.append(os.path.dirname(path)) |
0 | 34 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
|
35 sys.path.pop() |
0 | 36 else: |
37 module = import_dotted_path(path) | |
38 obj = module | |
39 while '.' in target: | |
40 attr, target = target.split('.', 1) | |
41 obj = getattr(obj, attr) | |
42 obj = getattr(obj, target) | |
43 return obj | |
44 else: | |
45 # module: dotted path | |
46 return import_dotted_path(string) | |
47 except: | |
48 print string | |
49 raise | |
50 | |
51 # TODO: entry points | |
52 | |
53 if __name__ == '__main__': | |
54 import sys | |
55 for i in sys.argv[1:]: | |
56 print load(i) |