KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > python > core > PySystemState


1 // Copyright (c) Corporation for National Research Initiatives
2

3 // This class implements the standard Python sys module.
4

5 package org.python.core;
6
7 import java.util.*;
8 import java.io.*;
9 import org.python.modules.Setup;
10
11 /**
12  * The "sys" module.
13  */

14
15 // xxx this should really be a module!
16
public class PySystemState extends PyObject
17 {
18     /**
19      * The current version of Jython.
20      */

21     public static String JavaDoc version = "2.2a1";
22
23     private static int PY_MAJOR_VERSION = 2;
24     private static int PY_MINOR_VERSION = 2;
25     private static int PY_MICRO_VERSION = 0;
26     private static int PY_RELEASE_LEVEL = 0xA;
27     private static int PY_RELEASE_SERIAL = 1;
28
29     public static int hexversion = ((PY_MAJOR_VERSION << 24) |
30                                     (PY_MINOR_VERSION << 16) |
31                                     (PY_MICRO_VERSION << 8) |
32                                     (PY_RELEASE_LEVEL << 4) |
33                                     (PY_RELEASE_SERIAL << 0));
34
35     public static PyTuple version_info;
36
37     public static int maxunicode = 65535;
38
39     /**
40      * The copyright notice for this release.
41      */

42     // TBD: should we use \u00a9 Unicode c-inside-circle?
43
public static String JavaDoc copyright =
44         "Copyright (c) 2000, Jython Developers\n" +
45         "All rights reserved.\n\n" +
46
47         "Copyright (c) 2000 BeOpen.com.\n" +
48         "All Rights Reserved.\n\n"+
49
50         "Copyright (c) 2000 The Apache Software Foundation. All rights\n" +
51         "reserved.\n\n" +
52
53         "Copyright (c) 1995-2000 Corporation for National Research "+
54         "Initiatives.\n" +
55         "All Rights Reserved.\n\n" +
56
57         "Copyright (c) 1991-1995 Stichting Mathematisch Centrum, " +
58         "Amsterdam.\n" +
59         "All Rights Reserved.\n\n";
60
61     /**
62      * The arguments passed to this program on the command line.
63      */

64     public PyList argv = new PyList();
65
66     /**
67      * Exit a Python program with the given status.
68      *
69      * @param status the value to exit with
70      * @exception Py.SystemExit always throws this exception.
71      * When caught at top level the program will exit.
72      */

73     public static void exit(PyObject status) {
74         throw new PyException(Py.SystemExit, status);
75     }
76
77     /**
78      * Exit a Python program with the status 0.
79      */

80     public static void exit() {
81         exit(Py.None);
82     }
83
84     public PyObject modules; // = new PyStringMap();
85
public PyList path;
86     public PyObject builtins;
87
88     public PyList meta_path;
89     public PyList path_hooks;
90     public PyObject path_importer_cache;
91
92     public static String JavaDoc platform = "java";
93     public static String JavaDoc byteorder = "big";
94
95     public PyObject ps1 = new PyString(">>> ");
96     public PyObject ps2 = new PyString("... ");
97
98     public static int maxint = Integer.MAX_VALUE;
99     public static int minint = Integer.MIN_VALUE;
100
101     public PyObject executable = Py.None;
102
103     public static PyList warnoptions;
104
105     private static PyJavaClass __builtin__class;
106
107     private ClassLoader JavaDoc classLoader = null;
108     public ClassLoader JavaDoc getClassLoader() {
109         return classLoader;
110     }
111     public void setClassLoader(ClassLoader JavaDoc classLoader) {
112         this.classLoader = classLoader;
113     }
114
115     public static PyTuple exc_info() {
116         PyException exc = Py.getThreadState().exception;
117         if (exc == null)
118             return new PyTuple(new PyObject[] {Py.None,Py.None,Py.None});
119         return new PyTuple(new PyObject[] {exc.type, exc.value,
120                                            exc.traceback});
121     }
122
123     public static PyFrame _getframe() {
124         return _getframe(-1);
125     }
126
127     public static PyFrame _getframe(int depth) {
128         PyFrame f = Py.getFrame();
129
130         while (depth > 0 && f != null) {
131             f = f.f_back;
132             --depth;
133         }
134         if (f == null)
135              throw Py.ValueError("call stack is not deep enough");
136         return f;
137     }
138
139     public PyObject stdout, stderr, stdin;
140     public PyObject __stdout__, __stderr__, __stdin__;
141
142     public PyObject __displayhook__, __excepthook__;
143
144     public PyObject last_value = Py.None;
145     public PyObject last_type = Py.None;
146     public PyObject last_traceback = Py.None;
147
148     // xxx fix this accessors
149
public PyObject __findattr__(String JavaDoc name) {
150         if (name == "exc_value") {
151             PyException exc = Py.getThreadState().exception;
152             if (exc == null) return null;
153             return exc.value;
154         }
155         if (name == "exc_type") {
156             PyException exc = Py.getThreadState().exception;
157             if (exc == null) return null;
158             return exc.type;
159         }
160         if (name == "exc_traceback") {
161             PyException exc = Py.getThreadState().exception;
162             if (exc == null) return null;
163             return exc.traceback;
164         }
165         if (name == "warnoptions") {
166             if (warnoptions == null)
167                 warnoptions = new PyList();
168             return warnoptions;
169         }
170
171         PyObject ret = super.__findattr__(name);
172         if (ret != null) return ret;
173
174         return __dict__.__finditem__(name);
175     }
176
177     public PyObject __dict__;
178     public void __setattr__(String JavaDoc name, PyObject value) {
179         PyType selftype = getType();
180         if (selftype == null)
181             return;
182         PyObject ret = selftype.lookup(name); // xxx fix fix fix
183
if (ret != null) {
184             ret.jtryset(this, value);
185             return;
186         }
187         if (__dict__ == null) {
188             __dict__ = new PyStringMap();
189         }
190         __dict__.__setitem__(name, value);
191         //throw Py.AttributeError(name);
192
}
193
194     public void __delattr__(String JavaDoc name) {
195         if (__dict__ != null) {
196             __dict__.__delitem__(name);
197             return;
198         }
199         throw Py.AttributeError("del '"+name+"'");
200     }
201
202     // xxx
203
public void __rawdir__(PyDictionary accum) {
204         accum.update(__dict__);
205     }
206
207     public String JavaDoc safeRepr() throws PyIgnoreMethodTag {
208         return "module 'sys'";
209     }
210
211     public String JavaDoc toString() {
212         return "sys module";
213     }
214
215     private int recursionlimit = 1000;
216
217     public int getrecursionlimit() {
218         return recursionlimit;
219     }
220
221     public void setrecursionlimit(int recursionlimit) {
222         this.recursionlimit = recursionlimit;
223     }
224
225     // xxx fix and polish this
226
public PySystemState() {
227         initialize();
228         modules = new PyStringMap();
229
230         argv = (PyList)defaultArgv.repeat(1);
231         path = (PyList)defaultPath.repeat(1);
232
233         meta_path = new PyList();
234         meta_path.append(new PrecompiledImporter());
235         meta_path.append(new JavaImporter());
236         path_hooks = new PyList();
237         path_hooks.append(PyJavaClass.lookup(ZipFileImporter.class));
238         path_importer_cache = new PyDictionary();
239
240         // Set up the initial standard ins and outs
241
__stdout__ = stdout = new PyFile(System.out, "<stdout>");
242         __stderr__ = stderr = new PyFile(System.err, "<stderr>");
243         __stdin__ = stdin = new PyFile(getSystemIn(), "<stdin>");
244         __displayhook__ = new PySystemStateFunctions("displayhook", 10, 1, 1);
245         __excepthook__ = new PySystemStateFunctions("excepthook", 30, 3, 3);
246
247         // This isn't quite right...
248
builtins = __builtin__class.__getattr__("__dict__");
249         PyModule __builtin__ = new PyModule("__builtin__", builtins);
250         modules.__setitem__("__builtin__", __builtin__);
251
252         if (getType() != null) {
253             __dict__ = new PyStringMap();
254             __dict__.invoke("update", getType().getDict());
255             __dict__.__setitem__("displayhook", __displayhook__);
256             __dict__.__setitem__("excepthook", __excepthook__);
257         }
258     }
259
260     private static PyList defaultPath;
261     private static PyList defaultArgv;
262
263     public static Properties registry; // = init_registry();
264
public static String JavaDoc prefix;
265     public static String JavaDoc exec_prefix="";
266
267     private static String JavaDoc findRoot(Properties preProperties,
268                                    Properties postProperties)
269     {
270         String JavaDoc root = null;
271         try {
272             if (postProperties != null)
273                 root = postProperties.getProperty("python.home");
274             if (root == null)
275                 root = preProperties.getProperty("python.home");
276             if (root == null)
277                 root = preProperties.getProperty("install.root");
278
279             String JavaDoc version = preProperties.getProperty("java.version");
280             if (version == null)
281                 version = "???";
282             String JavaDoc lversion = version.toLowerCase();
283             if (lversion.startsWith("java"))
284                 version = version.substring(4, version.length());
285
286             if (lversion.startsWith("jdk") || lversion.startsWith("jre")) {
287                 version = version.substring(3, version.length());
288             }
289             if (version.equals("11"))
290                 version = "1.1";
291             if (version.equals("12"))
292                 version = "1.2";
293             if (version != null)
294                 platform = "java"+version;
295         } catch (Exception JavaDoc exc) {
296             return null;
297         }
298         //System.err.println("root: "+root);
299
if (root != null)
300             return root;
301
302         // If install.root is undefined find jpython.jar in class.path
303
String JavaDoc classpath = preProperties.getProperty("java.class.path");
304         if (classpath == null)
305             return null;
306
307         int jpy = classpath.toLowerCase().indexOf("jython.jar");
308         if (jpy == -1) {
309             return null;
310         }
311         int start = classpath.lastIndexOf(java.io.File.pathSeparator, jpy)+1;
312         return classpath.substring(start, jpy);
313     }
314
315     private static void initRegistry(Properties preProperties,
316                                      Properties postProperties)
317     {
318         if (registry != null) {
319             Py.writeError("systemState", "trying to reinitialize registry");
320             return;
321         }
322
323         registry = preProperties;
324         prefix = exec_prefix = findRoot(preProperties, postProperties);
325
326         // Load the default registry
327
if (prefix != null) {
328             if (prefix.length() == 0) {
329                 prefix = exec_prefix = ".";
330             }
331             try {
332                 addRegistryFile(new File(prefix, "registry"));
333                 File homeFile = new File(registry.getProperty("user.home"),
334                                          ".jython");
335                 addRegistryFile(homeFile);
336             } catch (Exception JavaDoc exc) {
337                 ;
338             }
339         }
340         if (postProperties != null) {
341             for (Enumeration e=postProperties.keys(); e.hasMoreElements();)
342             {
343                 String JavaDoc key = (String JavaDoc)e.nextElement();
344                 String JavaDoc value = (String JavaDoc)postProperties.get(key);
345                 registry.put(key, value);
346             }
347         }
348         // Set up options from registry
349
Options.setFromRegistry();
350     }
351
352     private static void addRegistryFile(File file) {
353         if (file.exists()) {
354             registry = new Properties(registry);
355             try {
356                 FileInputStream fp = new FileInputStream(file);
357                 try {
358                     registry.load(fp);
359                 } finally {
360                     fp.close();
361                 }
362             } catch (IOException e) {
363                 System.err.println("couldn't open registry file: " +
364                                    file.toString());
365             }
366         }
367     }
368
369     private static boolean initialized = false;
370     public static synchronized void initialize() {
371         if (initialized)
372             return;
373         initialize(System.getProperties(), null, new String JavaDoc[] {""});
374     }
375
376     public static synchronized void initialize(Properties preProperties,
377                                                Properties postProperties,
378                                                String JavaDoc[] argv)
379     {
380         initialize(preProperties, postProperties, argv, null);
381     }
382
383     public static synchronized void initialize(Properties preProperties,
384                                                Properties postProperties,
385                                                String JavaDoc[] argv,
386                                                ClassLoader JavaDoc classLoader)
387     {
388
389         //System.err.println("initializing system state");
390
//Thread.currentThread().dumpStack();
391

392         if (initialized) {
393             //if (postProperties != null) {
394
// Py.writeError("systemState",
395
// "trying to reinitialize with new " +
396
// "properties");
397
//}
398
return;
399         }
400         initialized = true;
401
402         // initialize the JPython registry
403
initRegistry(preProperties, postProperties);
404
405         // other initializations
406
initBuiltins(registry);
407         initStaticFields();
408
409         // Initialize the path (and add system defaults)
410
defaultPath = initPath(registry);
411         defaultArgv = initArgv(argv);
412
413         // Set up the known Java packages
414
initPackages(registry);
415
416         // Finish up standard Python initialization...
417
Py.defaultSystemState = new PySystemState();
418         Py.setSystemState(Py.defaultSystemState);
419
420         if (classLoader != null)
421             Py.defaultSystemState.setClassLoader(classLoader);
422         Py.initClassExceptions(__builtin__class.__getattr__("__dict__"));
423         // Make sure that Exception classes have been loaded
424
new PySyntaxError("", 1,1,"", "");
425     }
426
427     private static void initStaticFields() {
428         Py.None = new PyNone();
429         Py.NotImplemented = new PyNotImplemented();
430         Py.NoKeywords = new String JavaDoc[0];
431         Py.EmptyObjects = new PyObject[0];
432
433         Py.EmptyTuple = new PyTuple(Py.EmptyObjects);
434         Py.NoConversion = new PySingleton("Error");
435         Py.Ellipsis = new PyEllipsis();
436
437         Py.Zero = new PyInteger(0);
438         Py.One = new PyInteger(1);
439
440         Py.EmptyString = new PyString("");
441         Py.Newline = new PyString("\n");
442         Py.Space = new PyString(" ");
443         // xxx what to do about modules
444
__builtin__class = PyJavaClass.lookup(__builtin__.class);
445
446         // Setup standard wrappers for stdout and stderr...
447
Py.stderr = new StderrWrapper();
448         Py.stdout = new StdoutWrapper();
449
450         String JavaDoc s = null;
451         if (PY_RELEASE_LEVEL == 0x0A)
452             s = "alpha";
453         else if (PY_RELEASE_LEVEL == 0x0B)
454             s = "beta";
455         else if (PY_RELEASE_LEVEL == 0x0C)
456             s = "candidate";
457         else if (PY_RELEASE_LEVEL == 0x0F)
458             s = "final";
459         version_info = new PyTuple(new PyObject[] {
460                             Py.newInteger(PY_MAJOR_VERSION),
461                             Py.newInteger(PY_MINOR_VERSION),
462                             Py.newInteger(PY_MICRO_VERSION),
463                             Py.newString(s),
464                             Py.newInteger(PY_RELEASE_SERIAL) });
465     }
466
467     public static PackageManager packageManager;
468     public static File cachedir;
469
470     private static void initCacheDirectory(Properties props) {
471         if (Py.frozen) {
472             cachedir = null;
473             return;
474         }
475         String JavaDoc skip = props.getProperty("python.cachedir.skip", "false");
476         if (skip.equalsIgnoreCase("true")) {
477             cachedir = null;
478             return;
479         }
480         cachedir = new File(props.getProperty("python.cachedir", "cachedir"));
481         if (!cachedir.isAbsolute()) {
482             cachedir = new File(PySystemState.prefix, cachedir.getPath());
483         }
484     }
485
486     private static void initPackages(Properties props) {
487         initCacheDirectory(props);
488         File pkgdir;
489         if (cachedir != null) {
490             pkgdir = new File(cachedir, "packages");
491         } else {
492             pkgdir = null;
493         }
494         packageManager = new SysPackageManager(pkgdir, props);
495     }
496
497     private static PyList initArgv(String JavaDoc[] args) {
498         PyList argv = new PyList();
499         if (args != null) {
500             for (int i=0; i<args.length; i++) {
501                 argv.append(new PyString(args[i]));
502             }
503         }
504         return argv;
505     }
506
507     private static Hashtable builtinNames;
508     public static String JavaDoc[] builtin_module_names = null;
509
510     private static void addBuiltin(String JavaDoc name) {
511         String JavaDoc classname;
512         String JavaDoc modname;
513
514         int colon = name.indexOf(':');
515         if (colon != -1) {
516             // name:fqclassname
517
modname = name.substring(0, colon).trim();
518             classname = name.substring(colon+1, name.length()).trim();
519             if (classname.equals("null"))
520                 // name:null, i.e. remove it
521
classname = null;
522         }
523         else {
524             modname = name.trim();
525             classname = "org.python.modules." + modname;
526         }
527         if (classname != null)
528             builtinNames.put(modname, classname);
529         else
530             builtinNames.remove(modname);
531     }
532
533     private static void initBuiltins(Properties props) {
534         builtinNames = new Hashtable();
535
536         // add builtins specified in the Setup.java file
537
for (int i=0; i < Setup.builtinModules.length; i++)
538             addBuiltin(Setup.builtinModules[i]);
539
540         // add builtins specified in the registry file
541
String JavaDoc builtinprop = props.getProperty("python.modules.builtin", "");
542         StringTokenizer tok = new StringTokenizer(builtinprop, ",");
543         while (tok.hasMoreTokens())
544             addBuiltin(tok.nextToken());
545
546         int n = builtinNames.size();
547         builtin_module_names = new String JavaDoc[n];
548         Enumeration keys = builtinNames.keys();
549         for (int i=0; i<n; i++)
550             builtin_module_names[i] = (String JavaDoc)keys.nextElement();
551     }
552
553     static String JavaDoc getBuiltin(String JavaDoc name) {
554         return (String JavaDoc)builtinNames.get(name);
555     }
556
557     private static PyList initPath(Properties props) {
558         PyList path = new PyList();
559         if (!Py.frozen) {
560             addPaths(path, props.getProperty("python.prepath", "."));
561
562             if (prefix != null) {
563                 String JavaDoc libpath = new File(prefix, "Lib").toString();
564                 path.append(new PyString(libpath));
565             }
566
567             addPaths(path, props.getProperty("python.path", ""));
568         }
569         return path;
570     }
571
572
573     private static void addPaths(PyList path, String JavaDoc pypath) {
574         StringTokenizer tok = new StringTokenizer(pypath,
575                                                   java.io.File.pathSeparator);
576         while (tok.hasMoreTokens())
577             path.append(new PyString(tok.nextToken().trim()));
578     }
579
580     public static PyJavaPackage add_package(String JavaDoc n) {
581         return add_package(n, null);
582     }
583
584     public static PyJavaPackage add_package(String JavaDoc n, String JavaDoc contents) {
585         return packageManager.makeJavaPackage(n, contents, null);
586     }
587
588     /**
589      * Add a classpath directory to the list of places that are searched
590      * for java packages.
591      * <p>
592      * <b>Note</b>. Classes found in directory and subdirectory are not
593      * made available to jython by this call. It only makes the java
594      * package found in the directory available. This call is mostly
595      * usefull if jython is embedded in an application that deals with
596      * its own classloaders. A servlet container is a very good example.
597      * Calling add_classdir("<context>/WEB-INF/classes") makes the java
598      * packages in WEB-INF classes available to jython import. However the
599      * actual classloading is completely handled by the servlet container's
600      * context classloader.
601      */

602     public static void add_classdir(String JavaDoc directoryPath) {
603         packageManager.addDirectory(new File(directoryPath));
604     }
605
606     /**
607      * Add a .jar & .zip directory to the list of places that are searched
608      * for java .jar and .zip files. The .jar and .zip files found will not
609      * be cached.
610      * <p>
611      * <b>Note</b>. Classes in .jar and .zip files found in the directory
612      * are not made available to jython by this call. See the note for
613      * add_classdir(dir) for more details.
614      *
615      * @param directoryPath The name of a directory.
616      *
617      * @see #add_classdir
618      */

619     public static void add_extdir(String JavaDoc directoryPath) {
620         packageManager.addJarDir(directoryPath, false);
621     }
622
623     /**
624      * Add a .jar & .zip directory to the list of places that are searched
625      * for java .jar and .zip files.
626      * <p>
627      * <b>Note</b>. Classes in .jar and .zip files found in the directory
628      * are not made available to jython by this call. See the note for
629      * add_classdir(dir) for more details.
630      *
631      * @param directoryPath The name of a directory.
632      * @param cache Controls if the packages in the zip and jar
633      * file should be cached.
634      *
635      * @see #add_classdir
636      */

637     public static void add_extdir(String JavaDoc directoryPath, boolean cache) {
638         packageManager.addJarDir(directoryPath, cache);
639     }
640
641     public TraceFunction tracefunc = null;
642     public TraceFunction profilefunc = null;
643
644     public void settrace(PyObject tracefunc) {
645         //InterpreterState interp = Py.getThreadState().interp;
646
if (tracefunc == Py.None) {
647             this.tracefunc = null;
648         } else {
649             this.tracefunc = new PythonTraceFunction(tracefunc);
650         }
651     }
652
653     public void setprofile(PyObject profilefunc) {
654         //InterpreterState interp = Py.getThreadState().interp;
655

656         if (profilefunc == Py.None) {
657             this.profilefunc = null;
658         } else {
659             this.profilefunc = new PythonTraceFunction(profilefunc);
660         }
661     }
662
663     private InputStream getSystemIn() {
664         if (Options.pollStandardIn) {
665             return new PollingInputStream(System.in);
666         } else {
667             return System.in;
668         }
669     }
670
671     public String JavaDoc getdefaultencoding() {
672         return codecs.getDefaultEncoding();
673     }
674
675     public void setdefaultencoding(String JavaDoc encoding) {
676         codecs.setDefaultEncoding(encoding);
677     }
678
679
680     // Not public by design. We can't rebind the displayhook if
681
// a reflected function is inserted in the class dict.
682

683     static void displayhook(PyObject o) {
684         /* Print value except if None */
685         /* After printing, also assign to '_' */
686         /* Before, set '_' to None to avoid recursion */
687         if (o == Py.None)
688              return;
689
690         PySystemState sys = Py.getThreadState().systemState;
691         sys.builtins.__setitem__("_", Py.None);
692         Py.stdout.println(o.__repr__());
693         sys.builtins.__setitem__("_", o);
694     }
695
696     static void excepthook(PyObject type, PyObject val, PyObject tb) {
697         Py.displayException(type, val, tb, null);
698     }
699
700     public void callExitFunc() throws PyIgnoreMethodTag {
701         PyObject exitfunc = __findattr__("exitfunc");
702         if (exitfunc != null) {
703             try {
704                 exitfunc.__call__();
705             } catch (PyException exc) {
706                 if (!Py.matchException(exc, Py.SystemExit)) {
707                     Py.println(stderr,
708                                Py.newString("Error in sys.exitfunc:"));
709                 }
710                 Py.printException(exc);
711             }
712         }
713     }
714 }
715
716
717 // This class is based on a suggestion from Yunho Jeon
718
class PollingInputStream extends FilterInputStream {
719     public PollingInputStream(InputStream s) {
720         super(s);
721     }
722
723     private void waitForBytes() throws IOException {
724         try {
725             while(available()==0) {
726                 //System.err.println("waiting...");
727
Thread.sleep(100);
728             }
729         } catch (InterruptedException JavaDoc e) {
730             throw new PyException(Py.KeyboardInterrupt,
731                                   "interrupt waiting on <stdin>");
732         }
733     }
734
735     public int read() throws IOException {
736         waitForBytes();
737         return super.read();
738     }
739
740     public int read(byte b[], int off, int len) throws IOException {
741         waitForBytes();
742         return super.read(b, off, len);
743     }
744 }
745
746
747 class PySystemStateFunctions extends PyBuiltinFunctionSet
748 {
749     PySystemStateFunctions(String JavaDoc name, int index, int minargs, int maxargs) {
750         super(name, index, minargs, maxargs, false, null);
751     }
752
753     public PyObject __call__(PyObject arg) {
754         switch (index) {
755         case 10:
756             PySystemState.displayhook(arg);
757             return Py.None;
758         default:
759             throw argCountError(1);
760         }
761     }
762     public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3) {
763         switch (index) {
764         case 30:
765             PySystemState.excepthook(arg1, arg2, arg3);
766             return Py.None;
767         default:
768             throw argCountError(3);
769         }
770     }
771 }
772
Popular Tags