blob: d5cfba314aca909dd5c743e22367f2f3f824bb56 [file] [log] [blame]
Guido van Rossum2d546921995-02-17 14:28:39 +00001"""Add a 'PYC ' resource named "__main__" to a resource file.
2
3This first puts up a dialog asking for a Python source file ('TEXT'),
4then one asking for an existing destination file ('APPL' or 'rsrc').
5
6It compiles the Python source into a code object, marshals it into a string,
7prefixes the string with a .pyc header, and turns it into a resource,
8which is then written to the destination.
9
10If the destination already contains a resource with the same name and type,
11it is overwritten.
12"""
13
14import marshal
15import imp
16import macfs
17from Res import *
18
19# .pyc file (and 'PYC ' resource magic number)
20MAGIC = imp.get_magic()
21
22# Complete specification of our resource
23RESTYPE = 'PYC '
24RESID = 128
25RESNAME = '__main__'
26
27# OpenResFile mode parameters
28READ = 1
29WRITE = 2
30
31def 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
88if __name__ == '__main__':
89 main()