Better example and comments.
[rox-lib.git] / python / rox / Pyrex / Mac / PyServerMain.py
blobd989de11c02c8516e6e5367ef4f06f121fc5fb13
2 # Simple Apple-event driven Python interpreter
5 import os, sys, traceback
6 from cStringIO import StringIO
7 from MiniAEFrame import AEServer, MiniApplication
9 class PythonServer(AEServer, MiniApplication):
11 def __init__(self):
12 MiniApplication.__init__(self)
13 AEServer.__init__(self)
14 self.installaehandler('aevt', 'oapp', ignore)
15 self.installaehandler('aevt', 'quit', quit)
16 self.installaehandler('misc', 'dosc', doscript)
19 def ignore(**kwds):
20 pass
22 def quit(**kwds):
23 server._quit()
25 def doscript(args, **kwds):
26 print "doscript:", repr(args) ###
27 stat = 0
28 output = ""
29 errput = ""
30 #print "Normalising args" ###
31 if type(args) == type(""):
32 args = [args]
33 #print "Setting sys.argv" ###
34 sys.argv = args
35 #print "Finding script directory and module file" ###
36 dir = os.path.dirname(args[0])
37 dir = os.path.join(start_dir, dir)
38 pyfile = os.path.basename(args[0])
39 mod = os.path.splitext(pyfile)[0]
40 #print "dir:", repr(dir) ###
41 #print "mod:", repr(mod) ###
42 os.chdir(dir)
43 sys.path = start_path[:]
44 sys.path[0] = dir
45 #print "path:", sys.path ###
46 try:
47 sys.stdout = StringIO()
48 sys.stderr = StringIO()
49 try:
50 #sys.__stdout__.write("Path: %s\n" % sys.path) ###
51 #sys.__stdout__.write("Importing: %s\n" % mod) ###
52 try:
53 __import__(mod)
54 except KeyboardInterrupt:
55 raise
56 except SystemExit, exc:
57 #sys.__stdout__.write("Caught a SystemExit\n") ###
58 try:
59 stat = int(str(exc))
60 except ValueError:
61 stat = 1
62 #sys.__stdout__.write("stat = %s\n" % stat) ###
63 except:
64 traceback.print_exc()
65 stat = 1
66 #sys.__stdout__.write("Done the import\n") ###
67 finally:
68 output = sys.stdout.getvalue()
69 #sys.__stdout__.write("Output:\n%s" % output) ###
70 errput = sys.stderr.getvalue()
71 finally:
72 sys.stdout = sys.__stdout__
73 sys.stderr = sys.__stdout__
74 pass
75 return [stat, output, errput]
77 start_dir = os.getcwd()
78 start_path = sys.path[:]
79 server = PythonServer()
80 #print "Open for business"
81 try:
82 server.mainloop()
83 except:
84 traceback.print_exc()
85 #sys.exit(1)
86 #print "Closing shop"