KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > python > util > jython


1 // Copyright (c) Corporation for National Research Initiatives
2
package org.python.util;
3
4 import org.python.core.*;
5 import java.util.zip.*;
6 import java.io.*;
7
8 public class jython
9 {
10     private static String JavaDoc usage =
11         "usage: jython [options] [-jar jar | -c cmd | file | -] [args]\n"+
12         "Options and arguments:\n"+
13         "-i : inspect interactively after running script, and force\n"+
14         " prompts, even if stdin does not appear to be a "+
15                     "terminal\n"+
16         "-S : don't imply `import site' on initialization\n"+
17         "-v : verbose (trace import statements)\n"+
18         "-Dprop=v : Set the property `prop' to value `v'\n"+
19         "-jar jar : program read from __run__.py in jar file\n"+
20         "-c cmd : program passed in as string (terminates option list)\n"+
21         "-W arg : warning control (arg is action:message:category:module:"+
22                     "lineno)\n"+
23         "-E codec : Use a different codec the reading from the console.\n"+
24         "-Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, " +
25                     "-Qnew\n"+
26         "file : program read from script file\n"+
27         "- : program read from stdin (default; interactive mode if a "+
28         "tty)\n"+
29         "--help : print this usage message and exit\n"+
30         "--version: print Jython version number and exit\n"+
31         "args : arguments passed to program in sys.argv[1:]";
32
33     public static void runJar(String JavaDoc filename) {
34         // TBD: this is kind of gross because a local called `zipfile' just
35
// magically shows up in the module's globals. Either `zipfile'
36
// should be called `__zipfile__' or (preferrably, IMO), __run__.py
37
// should be imported and a main() function extracted. This
38
// function should be called passing zipfile in as an argument.
39
//
40
// Probably have to keep this code around for backwards
41
// compatibility (?)
42
try {
43             ZipFile zip = new ZipFile(filename);
44
45             ZipEntry runit = zip.getEntry("__run__.py");
46             if (runit == null)
47                 throw Py.ValueError("jar file missing '__run__.py'");
48
49             PyStringMap locals = new PyStringMap();
50             locals.__setitem__("__name__", new PyString(filename));
51             locals.__setitem__("zipfile", Py.java2py(zip));
52
53             InputStream file = zip.getInputStream(runit);
54             PyCode code;
55             try {
56                 code = Py.compile(file, "__run__", "exec");
57             } finally {
58                 file.close();
59             }
60             Py.runCode(code, locals, locals);
61         } catch (java.io.IOException JavaDoc e) {
62             throw Py.IOError(e);
63         }
64     }
65
66     public static void main(String JavaDoc[] args) {
67         // Parse the command line options
68
CommandLineOptions opts = new CommandLineOptions();
69         if (!opts.parse(args)) {
70             if (opts.version) {
71                 System.err.println(InteractiveConsole.getDefaultBanner());
72                 System.exit(0);
73             }
74             System.err.println(usage);
75             int exitcode = opts.help ? 0 : -1;
76             System.exit(exitcode);
77         }
78
79         // Setup the basic python system state from these options
80
PySystemState.initialize(System.getProperties(),
81                                  opts.properties, opts.argv);
82
83         if (opts.notice) {
84             System.err.println(InteractiveConsole.getDefaultBanner());
85         }
86
87         // Now create an interpreter
88
InteractiveConsole interp = null;
89         try {
90             String JavaDoc interpClass = PySystemState.registry.getProperty(
91                                     "python.console",
92                                     "org.python.util.InteractiveConsole");
93             interp = (InteractiveConsole)
94                              Class.forName(interpClass).newInstance();
95         } catch (Exception JavaDoc e) {
96             interp = new InteractiveConsole();
97         }
98
99         //System.err.println("interp");
100
PyModule mod = imp.addModule("__main__");
101         interp.setLocals(mod.__dict__);
102         //System.err.println("imp");
103

104         for (int i = 0; i < opts.warnoptions.size(); i++) {
105             String JavaDoc wopt = (String JavaDoc) opts.warnoptions.elementAt(i);
106             PySystemState.warnoptions.append(new PyString(wopt));
107         }
108
109         String JavaDoc msg = "";
110         if (Options.importSite) {
111             try {
112                 imp.load("site");
113
114                 if (opts.notice) {
115                     PyObject builtins = Py.getSystemState().builtins;
116                     boolean copyright =
117                                 builtins.__finditem__("copyright") != null;
118                     boolean credits =
119                                 builtins.__finditem__("credits") != null;
120                     boolean license =
121                                 builtins.__finditem__("license") != null;
122                     if (copyright) {
123                         msg += "\"copyright\"";
124                         if (credits && license)
125                             msg += ", ";
126                         else if (credits || license)
127                             msg += " or ";
128                     }
129                     if (credits) {
130                         msg += "\"credits\"";
131                         if (license)
132                             msg += " or ";
133                     }
134                     if (license)
135                         msg += "\"license\"";
136                     if (msg.length() > 0)
137                         System.err.println("Type " + msg +
138                                            " for more information.");
139                 }
140             } catch (PyException pye) {
141                 if (!Py.matchException(pye, Py.ImportError)) {
142                     System.err.println("error importing site");
143                     Py.printException(pye);
144                     System.exit(-1);
145                 }
146             }
147         }
148
149         if (opts.division != null) {
150             if ("old".equals(opts.division))
151                 Options.divisionWarning = 0;
152             else if ("warn".equals(opts.division))
153                 Options.divisionWarning = 1;
154             else if ("warnall".equals(opts.division))
155                 Options.divisionWarning = 2;
156             else if ("new".equals(opts.division)) {
157                 Options.Qnew = true;
158                 interp.cflags.division = true;
159             }
160         }
161
162         if (opts.command != null) {
163             try {
164                 interp.exec(opts.command);
165             } catch (Throwable JavaDoc t) {
166                 Py.printException(t);
167             }
168         }
169
170         // was there a filename on the command line?
171
if (opts.filename != null) {
172             String JavaDoc path = new java.io.File JavaDoc(opts.filename).getParent();
173             if (path == null)
174                 path = "";
175             Py.getSystemState().path.insert(0, new PyString(path));
176             if (opts.jar) {
177                 runJar(opts.filename);
178             } else if (opts.filename.equals("-")) {
179                 try {
180                     interp.execfile(System.in, "<stdin>");
181                 } catch (Throwable JavaDoc t) {
182                     Py.printException(t);
183                 }
184             } else {
185                 try {
186                     interp.execfile(opts.filename);
187                 } catch (Throwable JavaDoc t) {
188                     Py.printException(t);
189                     if (!opts.interactive) {
190                         interp.cleanup();
191                         System.exit(-1);
192                     }
193                 }
194             }
195         }
196         else {
197             // if there was no file name on the command line, then "" is
198
// the first element on sys.path. This is here because if
199
// there /was/ a filename on the c.l., and say the -i option
200
// was given, sys.path[0] will have gotten filled in with the
201
// dir of the argument filename.
202
Py.getSystemState().path.insert(0, new PyString(""));
203         }
204
205         if (opts.interactive) {
206             if (opts.encoding == null) {
207                 opts.encoding = PySystemState.registry.getProperty(
208                                 "python.console.encoding", null);
209             }
210             if (opts.encoding != null) {
211                 interp.cflags.encoding = opts.encoding;
212             }
213             try {
214                 interp.interact(null);
215             } catch (Throwable JavaDoc t) {
216                 Py.printException(t);
217             }
218         }
219         interp.cleanup();
220         if (opts.interactive) {
221             System.exit(0);
222         }
223     }
224 }
225
226 class CommandLineOptions
227 {
228     public String JavaDoc filename;
229     public boolean jar, interactive, notice;
230     private boolean fixInteractive;
231     public boolean help, version;
232     public String JavaDoc[] argv;
233     public java.util.Properties JavaDoc properties;
234     public String JavaDoc command;
235     public java.util.Vector JavaDoc warnoptions = new java.util.Vector JavaDoc();
236     public String JavaDoc encoding;
237     public String JavaDoc division;
238
239     public CommandLineOptions() {
240         filename = null;
241         jar = fixInteractive = false;
242         interactive = notice = true;
243         properties = new java.util.Properties JavaDoc();
244         help = version = false;
245     }
246
247     public void setProperty(String JavaDoc key, String JavaDoc value) {
248         properties.put(key, value);
249         // This only works for Java 1.2. There appears to be no portable
250
// way to support this under Java 1.1
251
// try {
252
// System.setProperty(key, value);
253
// }
254
// catch (SecurityException e) {}
255
}
256
257     public boolean parse(String JavaDoc[] args) {
258         int index=0;
259         while (index < args.length && args[index].startsWith("-")) {
260             String JavaDoc arg = args[index];
261             if (arg.equals("--help")) {
262                 help = true;
263                 return false;
264             }
265             else if (arg.equals("--version")) {
266                 version = true;
267                 return false;
268             }
269             else if (arg.equals("-")) {
270                 if (!fixInteractive)
271                     interactive = false;
272                 filename = "-";
273             }
274             else if (arg.equals("-i")) {
275                 fixInteractive = true;
276                 interactive = true;
277             }
278             else if (arg.equals("-jar")) {
279                 jar = true;
280                 if (!fixInteractive)
281                     interactive = false;
282             }
283             else if (arg.equals("-v")) {
284                 Options.verbose++;
285             }
286             else if (arg.equals("-vv")) {
287                 Options.verbose += 2;
288             }
289             else if (arg.equals("-vvv")) {
290                 Options.verbose +=3 ;
291             }
292             else if (arg.equals("-S")) {
293                 Options.importSite = false;
294             }
295             else if (arg.equals("-c")) {
296                 command = args[++index];
297                 if (!fixInteractive) interactive = false;
298                 index++;
299                 break;
300             }
301             else if (arg.equals("-W")) {
302                 warnoptions.addElement(args[++index]);
303             }
304             else if (arg.equals("-E")) {
305                 encoding = args[++index];
306             }
307             else if (arg.startsWith("-D")) {
308                 String JavaDoc key = null;
309                 String JavaDoc value = null;
310                 int equals = arg.indexOf("=");
311                 if (equals == -1) {
312                     String JavaDoc arg2 = args[++index];
313                     key = arg.substring(2, arg.length());
314                     value = arg2;
315                 }
316                 else {
317                     key = arg.substring(2, equals);
318                     value = arg.substring(equals+1, arg.length());
319                 }
320                 setProperty(key, value);
321             }
322             else if (arg.startsWith("-Q")) {
323                 if (arg.length() > 2)
324                     division = arg.substring(2);
325                 else
326                     division = args[++index];
327             }
328             else {
329                 String JavaDoc opt = args[index];
330                 if (opt.startsWith("--"))
331                     opt = opt.substring(2);
332                 else if (opt.startsWith("-"))
333                     opt = opt.substring(1);
334                 System.err.println("jython: illegal option -- " + opt);
335                 return false;
336             }
337             index += 1;
338         }
339         notice = interactive;
340         if (filename == null && index < args.length && command == null) {
341             filename = args[index++];
342             if (!fixInteractive)
343                 interactive = false;
344             notice = false;
345         }
346         if (command != null)
347             notice = false;
348
349         int n = args.length-index+1;
350         argv = new String JavaDoc[n];
351         //new String[args.length-index+1];
352
if (filename != null)
353             argv[0] = filename;
354         else if (command != null)
355             argv[0] = "-c";
356         else
357             argv[0] = "";
358
359         for(int i=1; i<n; i++, index++) {
360             argv[i] = args[index];
361         }
362
363         return true;
364     }
365 }
366
Popular Tags