Jack Jansen | de3226f | 2001-08-27 21:21:07 +0000 | [diff] [blame^] | 1 | """macresource - Locate and open the resources needed for a script.""" |
| 2 | |
| 3 | from Carbon import Res |
| 4 | import os |
| 5 | import sys |
| 6 | |
| 7 | class ArgumentError(TypeError): pass |
| 8 | class ResourceFileNotFoundError(ImportError): pass |
| 9 | |
| 10 | def need(restype, resid, filename=None, modname=None): |
| 11 | """Open a resource file, if needed. restype and resid |
| 12 | are required parameters, and identify the resource for which to test. If it |
| 13 | is available we are done. If it is not available we look for a file filename |
| 14 | (default: modname with .rsrc appended) either in the same folder as |
| 15 | where modname was loaded from, or otherwise across sys.path.""" |
| 16 | |
| 17 | if modname is None and filename is None: |
| 18 | raise ArgumentError, "Either filename or modname argument (or both) must be given" |
| 19 | |
| 20 | if type(resid) is type(1): |
| 21 | try: |
| 22 | h = Res.GetResource(restype, resid) |
| 23 | except Res.Error: |
| 24 | pass |
| 25 | else: |
| 26 | return |
| 27 | else: |
| 28 | try: |
| 29 | h = Res.GetNamedResource(restype, resid) |
| 30 | except Res.Error: |
| 31 | pass |
| 32 | else: |
| 33 | return |
| 34 | |
| 35 | # Construct a filename if we don't have one |
| 36 | if not filename: |
| 37 | if '.' in modname: |
| 38 | filename = modname.split('.')[-1] + '.rsrc' |
| 39 | else: |
| 40 | filename = modname + '.rsrc' |
| 41 | |
| 42 | # Now create a list of folders to search |
| 43 | searchdirs = [] |
| 44 | if modname == '__main__': |
| 45 | # If we're main we look in the current directory |
| 46 | searchdirs = [os.curdir] |
| 47 | if sys.modules.has_key(modname): |
| 48 | mod = sys.modules[modname] |
| 49 | if hasattr(mod, '__file__'): |
| 50 | searchdirs = [mod.__file__] |
| 51 | if not searchdirs: |
| 52 | searchdirs = sys.path |
| 53 | |
| 54 | # And look for the file |
| 55 | for dir in searchdirs: |
| 56 | pathname = os.path.join(dir, filename) |
| 57 | if os.path.exists(pathname): |
| 58 | break |
| 59 | else: |
| 60 | raise ResourceFileNotFoundError, filename |
| 61 | |
| 62 | Res.FSpOpenResFile(pathname, 1) |
| 63 | |
| 64 | # And check that the resource exists now |
| 65 | if type(resid) is type(1): |
| 66 | h = Res.GetResource(restype, resid) |
| 67 | else: |
| 68 | h = Res.GetNamedResource(restype, resid) |