Guido van Rossum | 2d54692 | 1995-02-17 14:28:39 +0000 | [diff] [blame^] | 1 | """Add a 'PYC ' resource named "__main__" to a resource file. |
| 2 | |
| 3 | This first puts up a dialog asking for a Python source file ('TEXT'), |
| 4 | then one asking for an existing destination file ('APPL' or 'rsrc'). |
| 5 | |
| 6 | It compiles the Python source into a code object, marshals it into a string, |
| 7 | prefixes the string with a .pyc header, and turns it into a resource, |
| 8 | which is then written to the destination. |
| 9 | |
| 10 | If the destination already contains a resource with the same name and type, |
| 11 | it is overwritten. |
| 12 | """ |
| 13 | |
| 14 | import marshal |
| 15 | import imp |
| 16 | import macfs |
| 17 | from Res import * |
| 18 | |
| 19 | # .pyc file (and 'PYC ' resource magic number) |
| 20 | MAGIC = imp.get_magic() |
| 21 | |
| 22 | # Complete specification of our resource |
| 23 | RESTYPE = 'PYC ' |
| 24 | RESID = 128 |
| 25 | RESNAME = '__main__' |
| 26 | |
| 27 | # OpenResFile mode parameters |
| 28 | READ = 1 |
| 29 | WRITE = 2 |
| 30 | |
| 31 | def main(): |
| 32 | |
| 33 | # Ask for source text |
| 34 | |
| 35 | srcfss, ok = macfs.StandardGetFile('TEXT') |
| 36 | if not ok: return |
| 37 | |
| 38 | # Read the source and compile it |
| 39 | # (there's no point asking for a destination if it has a syntax error) |
| 40 | |
| 41 | filename = srcfss.as_pathname() |
| 42 | fp = open(filename) |
| 43 | text = fp.read() |
| 44 | fp.close() |
| 45 | code = compile(text, filename, "exec") |
| 46 | |
| 47 | # Ask for destination file |
| 48 | |
| 49 | dstfss, ok = macfs.StandardGetFile('APPL', 'rsrc') |
| 50 | if not ok: return |
| 51 | |
| 52 | # Create the raw data for the resource from the code object |
| 53 | |
| 54 | data = marshal.dumps(code) |
| 55 | del code |
| 56 | data = (MAGIC + '\0\0\0\0') + data |
| 57 | |
| 58 | # Open the resource file |
| 59 | |
| 60 | fnum = FSpOpenResFile(dstfss.as_pathname(), WRITE) |
| 61 | |
| 62 | # Delete any existing resource with name __main__ or number 128 |
| 63 | |
| 64 | try: |
| 65 | res = Get1NamedResource(RESTYPE, RESNAME) |
| 66 | res.RmveResource() |
| 67 | except Error: |
| 68 | pass |
| 69 | |
| 70 | try: |
| 71 | res = Get1Resource(RESTYPE, RESID) |
| 72 | res.RmveResource() |
| 73 | except Error: |
| 74 | pass |
| 75 | |
| 76 | # Create the resource and write it |
| 77 | |
| 78 | res = Resource(data) |
| 79 | res.AddResource(RESTYPE, RESID, RESNAME) |
| 80 | # XXX Are the following two calls needed? |
| 81 | res.WriteResource() |
| 82 | res.ReleaseResource() |
| 83 | |
| 84 | # Close the resource file |
| 85 | |
| 86 | CloseResFile(fnum) |
| 87 | |
| 88 | if __name__ == '__main__': |
| 89 | main() |