1 3 5 package org.python.core; 6 7 import java.util.*; 8 import java.io.*; 9 import org.python.modules.Setup; 10 11 14 15 public class PySystemState extends PyObject 17 { 18 21 public static String 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 42 public static String 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 64 public PyList argv = new PyList(); 65 66 73 public static void exit(PyObject status) { 74 throw new PyException(Py.SystemExit, status); 75 } 76 77 80 public static void exit() { 81 exit(Py.None); 82 } 83 84 public PyObject modules; 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 platform = "java"; 93 public static String 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 classLoader = null; 108 public ClassLoader getClassLoader() { 109 return classLoader; 110 } 111 public void setClassLoader(ClassLoader 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 public PyObject __findattr__(String 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 name, PyObject value) { 179 PyType selftype = getType(); 180 if (selftype == null) 181 return; 182 PyObject ret = selftype.lookup(name); 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 } 193 194 public void __delattr__(String name) { 195 if (__dict__ != null) { 196 __dict__.__delitem__(name); 197 return; 198 } 199 throw Py.AttributeError("del '"+name+"'"); 200 } 201 202 public void __rawdir__(PyDictionary accum) { 204 accum.update(__dict__); 205 } 206 207 public String safeRepr() throws PyIgnoreMethodTag { 208 return "module 'sys'"; 209 } 210 211 public String 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 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 __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 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; public static String prefix; 265 public static String exec_prefix=""; 266 267 private static String findRoot(Properties preProperties, 268 Properties postProperties) 269 { 270 String 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 version = preProperties.getProperty("java.version"); 280 if (version == null) 281 version = "???"; 282 String 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 exc) { 296 return null; 297 } 298 if (root != null) 300 return root; 301 302 String 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 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 exc) { 337 ; 338 } 339 } 340 if (postProperties != null) { 341 for (Enumeration e=postProperties.keys(); e.hasMoreElements();) 342 { 343 String key = (String )e.nextElement(); 344 String value = (String )postProperties.get(key); 345 registry.put(key, value); 346 } 347 } 348 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 [] {""}); 374 } 375 376 public static synchronized void initialize(Properties preProperties, 377 Properties postProperties, 378 String [] argv) 379 { 380 initialize(preProperties, postProperties, argv, null); 381 } 382 383 public static synchronized void initialize(Properties preProperties, 384 Properties postProperties, 385 String [] argv, 386 ClassLoader classLoader) 387 { 388 389 392 if (initialized) { 393 return; 399 } 400 initialized = true; 401 402 initRegistry(preProperties, postProperties); 404 405 initBuiltins(registry); 407 initStaticFields(); 408 409 defaultPath = initPath(registry); 411 defaultArgv = initArgv(argv); 412 413 initPackages(registry); 415 416 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 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 [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 __builtin__class = PyJavaClass.lookup(__builtin__.class); 445 446 Py.stderr = new StderrWrapper(); 448 Py.stdout = new StdoutWrapper(); 449 450 String 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 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 [] 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 [] builtin_module_names = null; 509 510 private static void addBuiltin(String name) { 511 String classname; 512 String modname; 513 514 int colon = name.indexOf(':'); 515 if (colon != -1) { 516 modname = name.substring(0, colon).trim(); 518 classname = name.substring(colon+1, name.length()).trim(); 519 if (classname.equals("null")) 520 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 for (int i=0; i < Setup.builtinModules.length; i++) 538 addBuiltin(Setup.builtinModules[i]); 539 540 String 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 [n]; 548 Enumeration keys = builtinNames.keys(); 549 for (int i=0; i<n; i++) 550 builtin_module_names[i] = (String )keys.nextElement(); 551 } 552 553 static String getBuiltin(String name) { 554 return (String )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 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 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 n) { 581 return add_package(n, null); 582 } 583 584 public static PyJavaPackage add_package(String n, String contents) { 585 return packageManager.makeJavaPackage(n, contents, null); 586 } 587 588 602 public static void add_classdir(String directoryPath) { 603 packageManager.addDirectory(new File(directoryPath)); 604 } 605 606 619 public static void add_extdir(String directoryPath) { 620 packageManager.addJarDir(directoryPath, false); 621 } 622 623 637 public static void add_extdir(String 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 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 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 getdefaultencoding() { 672 return codecs.getDefaultEncoding(); 673 } 674 675 public void setdefaultencoding(String encoding) { 676 codecs.setDefaultEncoding(encoding); 677 } 678 679 680 683 static void displayhook(PyObject o) { 684 685 686 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 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 Thread.sleep(100); 728 } 729 } catch (InterruptedException 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 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 |