You can subscribe to this list here.
2000 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(1) |
Nov
(107) |
Dec
(67) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2001 |
Jan
(76) |
Feb
(125) |
Mar
(72) |
Apr
(13) |
May
(18) |
Jun
(12) |
Jul
(129) |
Aug
(47) |
Sep
(1) |
Oct
(36) |
Nov
(128) |
Dec
(124) |
2002 |
Jan
(59) |
Feb
|
Mar
(14) |
Apr
(14) |
May
(72) |
Jun
(9) |
Jul
(3) |
Aug
(5) |
Sep
(18) |
Oct
(65) |
Nov
(28) |
Dec
(12) |
2003 |
Jan
(10) |
Feb
(2) |
Mar
(4) |
Apr
(33) |
May
(21) |
Jun
(9) |
Jul
(29) |
Aug
(34) |
Sep
(4) |
Oct
(8) |
Nov
(15) |
Dec
(4) |
2004 |
Jan
(26) |
Feb
(12) |
Mar
(11) |
Apr
(9) |
May
(7) |
Jun
|
Jul
(5) |
Aug
|
Sep
(3) |
Oct
(7) |
Nov
(1) |
Dec
(10) |
2005 |
Jan
(2) |
Feb
(72) |
Mar
(16) |
Apr
(39) |
May
(48) |
Jun
(97) |
Jul
(57) |
Aug
(13) |
Sep
(16) |
Oct
(24) |
Nov
(100) |
Dec
(24) |
2006 |
Jan
(15) |
Feb
(34) |
Mar
(33) |
Apr
(31) |
May
(79) |
Jun
(64) |
Jul
(41) |
Aug
(64) |
Sep
(31) |
Oct
(46) |
Nov
(55) |
Dec
(37) |
2007 |
Jan
(32) |
Feb
(61) |
Mar
(11) |
Apr
(58) |
May
(46) |
Jun
(30) |
Jul
(94) |
Aug
(93) |
Sep
(86) |
Oct
(69) |
Nov
(125) |
Dec
(177) |
2008 |
Jan
(169) |
Feb
(97) |
Mar
(74) |
Apr
(113) |
May
(120) |
Jun
(334) |
Jul
(215) |
Aug
(237) |
Sep
(72) |
Oct
(189) |
Nov
(126) |
Dec
(160) |
2009 |
Jan
(180) |
Feb
(45) |
Mar
(98) |
Apr
(140) |
May
(151) |
Jun
(71) |
Jul
(107) |
Aug
(119) |
Sep
(73) |
Oct
(121) |
Nov
(14) |
Dec
(6) |
2010 |
Jan
(13) |
Feb
(9) |
Mar
(10) |
Apr
(64) |
May
(3) |
Jun
(16) |
Jul
(7) |
Aug
(23) |
Sep
(17) |
Oct
(37) |
Nov
(5) |
Dec
(8) |
2011 |
Jan
(10) |
Feb
(11) |
Mar
(77) |
Apr
(11) |
May
(2) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: <pj...@us...> - 2009-10-20 00:54:09
|
Revision: 6879 http://jython.svn.sourceforge.net/jython/?rev=6879&view=rev Author: pjenvey Date: 2009-10-20 00:54:00 +0000 (Tue, 20 Oct 2009) Log Message: ----------- o constantine lacks sensible Windows OpenFlags constants, roll our own o fix put/unset/getenv on Windows Modified Paths: -------------- trunk/jython/Lib/posix.py trunk/jython/src/org/python/modules/posix/PosixModule.java Modified: trunk/jython/Lib/posix.py =================================================================== --- trunk/jython/Lib/posix.py 2009-10-20 00:20:58 UTC (rev 6878) +++ trunk/jython/Lib/posix.py 2009-10-20 00:54:00 UTC (rev 6879) @@ -320,7 +320,6 @@ try: fchannel = RandomAccessFile(sys.getPath(filename), 'rws').getChannel() except FileNotFoundException, fnfe: - #if path.isdir(filename): if _stat.S_ISDIR(stat(filename).st_mode): raise OSError(errno.EISDIR, strerror(errno.EISDIR)) raise OSError(errno.ENOENT, strerror(errno.ENOENT), filename) @@ -414,20 +413,26 @@ Change or add an environment variable. """ - environ[key] = value + # XXX: put/unset/getenv should probably be deprecated + import os + os.environ[key] = value def unsetenv(key): """unsetenv(key) Delete an environment variable. """ - if key in environ: - del environ[key] + import os + try: + del os.environ[key] + except KeyError: + pass def getenv(key, default=None): """Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default.""" - return environ.get(key, default) + import os + return os.environ.get(key, default) if _name == 'posix': def link(src, dst): Modified: trunk/jython/src/org/python/modules/posix/PosixModule.java =================================================================== --- trunk/jython/src/org/python/modules/posix/PosixModule.java 2009-10-20 00:20:58 UTC (rev 6878) +++ trunk/jython/src/org/python/modules/posix/PosixModule.java 2009-10-20 00:54:00 UTC (rev 6879) @@ -2,7 +2,6 @@ package org.python.modules.posix; import com.kenai.constantine.Constant; -import com.kenai.constantine.ConstantSet; import com.kenai.constantine.platform.Errno; import org.jruby.ext.posix.JavaPOSIX; @@ -39,18 +38,20 @@ /** Platform specific POSIX services. */ private static POSIX posix = POSIXFactory.getPOSIX(new PythonPOSIXHandler(), true); - private static final String[] openFlags = - {"O_RDONLY", "O_WRONLY", "O_RDWR", "O_APPEND", "O_SYNC", "O_CREAT", "O_TRUNC", "O_EXCL"}; - public static void classDictInit(PyObject dict) { dict.__setitem__("__name__", new PyString("_" + os.getModuleName())); dict.__setitem__("__doc__", __doc__); // os.open flags, only expose what we support - ConstantSet openFlagConstants = ConstantSet.getConstantSet("OpenFlags"); - for (String openFlag : openFlags) { - dict.__setitem__(openFlag, Py.newInteger(openFlagConstants.getValue(openFlag))); - } + dict.__setitem__("O_RDONLY", Py.newInteger(0x0)); + dict.__setitem__("O_WRONLY", Py.newInteger(0x1)); + dict.__setitem__("O_RDWR", Py.newInteger(0x2)); + dict.__setitem__("O_APPEND", Py.newInteger(0x8)); + dict.__setitem__("O_SYNC", Py.newInteger(0x80)); + dict.__setitem__("O_CREAT", Py.newInteger(0x200)); + dict.__setitem__("O_TRUNC", Py.newInteger(0x400)); + dict.__setitem__("O_EXCL", Py.newInteger(0x800)); + // os.access constants dict.__setitem__("F_OK", Py.Zero); dict.__setitem__("X_OK", Py.newInteger(1 << 0)); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-20 00:21:20
|
Revision: 6878 http://jython.svn.sourceforge.net/jython/?rev=6878&view=rev Author: pjenvey Date: 2009-10-20 00:20:58 +0000 (Tue, 20 Oct 2009) Log Message: ----------- o jna-posix does the pure java stat for us, simplify it + move it to PosixModule o move strerror to PosixModule because it does the work of falling back to Linux errno descriptions on Windows, and we need that from some Java calls Modified Paths: -------------- trunk/jython/Lib/posix.py trunk/jython/Lib/test/test_fileno.py trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/modules/posix/PosixModule.java trunk/jython/src/org/python/modules/posix/PyStatResult.java trunk/jython/src/org/python/modules/posix/PythonPOSIXHandler.java Modified: trunk/jython/Lib/posix.py =================================================================== --- trunk/jython/Lib/posix.py 2009-10-20 00:06:05 UTC (rev 6877) +++ trunk/jython/Lib/posix.py 2009-10-20 00:20:58 UTC (rev 6878) @@ -18,18 +18,14 @@ from java.io import File from org.python.core.io import FileDescriptors, FileIO, IOBase from org.python.core.Py import newString as asPyString -try: - from org.python.constantine.platform import Errno -except ImportError: - from com.kenai.constantine.platform import Errno __all__ = _posix.__all__[:] __all__.extend(['_exit', 'access', 'chdir', 'chmod', 'close', 'environ', 'fdopen', 'fsync', 'ftruncate', 'getcwd', 'getcwdu', 'getenv', - 'getpid', 'isatty', 'listdir', 'lseek', 'lstat', 'mkdir', - 'open', 'popen', 'putenv', 'read', 'remove', 'rename', 'rmdir', - 'stat', 'strerror', 'system', 'umask', 'unlink', 'unsetenv', - 'urandom', 'utime', 'write']) + 'getpid', 'isatty', 'listdir', 'lseek', 'mkdir', 'open', + 'popen', 'putenv', 'read', 'remove', 'rename', 'rmdir', + 'system', 'umask', 'unlink', 'unsetenv', 'urandom', 'utime', + 'write']) _name = _posix.__name__[1:] @@ -151,28 +147,6 @@ elif not f.delete(): raise OSError(0, "couldn't delete directory", path) -def strerror(code): - """strerror(code) -> string - - Translate an error code to a message string. - """ - if not isinstance(code, (int, long)): - raise TypeError('an integer is required') - constant = Errno.valueOf(code) - if constant is Errno.__UNKNOWN_CONSTANT__: - return 'Unknown error: %d' % code - if constant.name() == constant.description(): - # XXX: have constantine handle this fallback - # Fake constant or just lacks a description, fallback to Linux's - try: - from org.python.constantine.platform.linux import Errno as LinuxErrno - except ImportError: - from com.kenai.constantine.platform.linux import Errno as LinuxErrno - constant = getattr(LinuxErrno, constant.name(), None) - if not constant: - return 'Unknown error: %d' % code - return asPyString(constant.toString()) - def access(path, mode): """access(path, mode) -> True if granted, False otherwise @@ -201,75 +175,6 @@ result = False return result -def stat(path): - """stat(path) -> stat result - - Perform a stat system call on the given path. - - The Java stat implementation only returns a small subset of - the standard fields: size, modification time and change time. - """ - abs_path = sys.getPath(path) - try: - return _from_jnastat(_posix_impl.stat(abs_path)) - except NotImplementedError: - pass - f = File(abs_path) - if not f.exists(): - raise OSError(errno.ENOENT, strerror(errno.ENOENT), path) - size = f.length() - mtime = f.lastModified() / 1000.0 - mode = 0 - if f.isDirectory(): - mode = _stat.S_IFDIR - elif f.isFile(): - mode = _stat.S_IFREG - if f.canRead(): - mode = mode | _stat.S_IREAD - if f.canWrite(): - mode = mode | _stat.S_IWRITE - return stat_result((mode, 0, 0, 0, 0, 0, size, mtime, mtime, 0)) - -def lstat(path): - """lstat(path) -> stat result - - Like stat(path), but do not follow symbolic links. - """ - abs_path = sys.getPath(path) - try: - return _from_jnastat(_posix_impl.lstat(abs_path)) - except NotImplementedError: - pass - f = File(sys.getPath(path)) - # XXX: jna-posix implements similar link detection in - # JavaFileStat.calculateSymlink, fallback to that instead when not - # native - abs_parent = f.getAbsoluteFile().getParentFile() - if not abs_parent: - # root isn't a link - return stat(path) - can_parent = abs_parent.getCanonicalFile() - - if can_parent.getAbsolutePath() == abs_parent.getAbsolutePath(): - # The parent directory's absolute path is canonical.. - if f.getAbsolutePath() != f.getCanonicalPath(): - # but the file's absolute and canonical paths differ (a - # link) - return stat_result((_stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0)) - - # The parent directory's path is not canonical (one of the parent - # directories is a symlink). Build a new path with the parent's - # canonical path and compare the files - f = File(can_parent.getAbsolutePath(), f.getName()) - if f.getAbsolutePath() != f.getCanonicalPath(): - return stat_result((_stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0)) - - # Not a link, only now can we determine if it exists (because - # File.exists() returns False for dead links) - if not f.exists(): - raise OSError(errno.ENOENT, strerror(errno.ENOENT), path) - return stat(path) - def utime(path, times): """utime(path, (atime, mtime)) utime(path, None) @@ -723,13 +628,3 @@ buffer = jarray.zeros(n, 'b') urandom_source.nextBytes(buffer) return buffer.tostring() - -def _from_jnastat(s): - results = [] - for meth in (s.mode, s.ino, s.dev, s.nlink, s.uid, s.gid, s.st_size, - s.atime, s.mtime, s.ctime): - try: - results.append(meth()) - except NotImplementedError: - results.append(0) - return stat_result(results) Modified: trunk/jython/Lib/test/test_fileno.py =================================================================== --- trunk/jython/Lib/test/test_fileno.py 2009-10-20 00:06:05 UTC (rev 6877) +++ trunk/jython/Lib/test/test_fileno.py 2009-10-20 00:20:58 UTC (rev 6878) @@ -327,7 +327,7 @@ except exc, val: if expected and str(val) != msg: raise test_support.TestFailed( - "Message %r, expected %r" % (str(value), msg)) + "Message %r, expected %r" % (str(val), msg)) else: raise test_support.TestFailed("Expected %s" % exc) Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2009-10-20 00:06:05 UTC (rev 6877) +++ trunk/jython/src/org/python/core/Py.java 2009-10-20 00:20:58 UTC (rev 6878) @@ -27,6 +27,7 @@ import java.util.List; import org.python.core.adapter.ClassicPyObjectAdapter; import org.python.core.adapter.ExtensiblePyObjectAdapter; +import org.python.modules.posix.PosixModule; import org.python.util.Generic; public final class Py { @@ -104,7 +105,10 @@ } public static PyException OSError(Constant errno, String filename) { - PyObject args = new PyTuple(Py.newInteger(errno.value()), Py.newString(errno.toString()), + int value = errno.value(); + // Pass to strerror because constantine currently lacks Errno descriptions on + // Windows, and strerror falls back to Linux's + PyObject args = new PyTuple(Py.newInteger(value), PosixModule.strerror(value), Py.newString(filename)); return new PyException(Py.OSError, args); } @@ -171,12 +175,14 @@ } public static PyException IOError(Constant errno) { - PyObject args = new PyTuple(Py.newInteger(errno.value()), Py.newString(errno.toString())); + int value = errno.value(); + PyObject args = new PyTuple(Py.newInteger(value), PosixModule.strerror(value)); return new PyException(Py.IOError, args); } public static PyException IOError(Constant errno, String filename) { - PyObject args = new PyTuple(Py.newInteger(errno.value()), Py.newString(errno.toString()), + int value = errno.value(); + PyObject args = new PyTuple(Py.newInteger(value), PosixModule.strerror(value), Py.newString(filename)); return new PyException(Py.IOError, args); } Modified: trunk/jython/src/org/python/modules/posix/PosixModule.java =================================================================== --- trunk/jython/src/org/python/modules/posix/PosixModule.java 2009-10-20 00:06:05 UTC (rev 6877) +++ trunk/jython/src/org/python/modules/posix/PosixModule.java 2009-10-20 00:20:58 UTC (rev 6878) @@ -1,7 +1,9 @@ /* Copyright (c) Jython Developers */ package org.python.modules.posix; +import com.kenai.constantine.Constant; import com.kenai.constantine.ConstantSet; +import com.kenai.constantine.platform.Errno; import org.jruby.ext.posix.JavaPOSIX; import org.jruby.ext.posix.POSIX; @@ -70,6 +72,39 @@ dict.__setitem__("__all__", dict.invoke("keys")); } + public static PyString __doc__lstat = new PyString( + "lstat(path) -> stat result\n\n" + + "Like stat(path), but do not follow symbolic links."); + public static PyObject lstat(String path) { + return PyStatResult.fromFileStat(posix.lstat(Py.getSystemState().getPath(path))); + } + + public static PyString __doc__stat = new PyString( + "stat(path) -> stat result\n\n" + + "Perform a stat system call on the given path.\n\n" + + "Note that some platforms may return only a small subset of the\n" + + "standard fields"); + public static PyObject stat(String path) { + return PyStatResult.fromFileStat(posix.stat(Py.getSystemState().getPath(path))); + } + + public static PyString __doc__strerror = new PyString( + "strerror(code) -> string\n\n" + + "Translate an error code to a message string."); + public static PyObject strerror(int code) { + Constant errno = Errno.valueOf(code); + if (errno == Errno.__UNKNOWN_CONSTANT__) { + return new PyString("Unknown error: " + code); + } + if (errno.name() == errno.toString()) { + // Fake constant or just lacks a description, fallback to Linux's + // XXX: have constantine handle this fallback + errno = Enum.valueOf(com.kenai.constantine.platform.linux.Errno.class, + errno.name()); + } + return new PyString(errno.toString()); + } + /** * Helper function for the subprocess module, returns the potential shell commands for * this OS. Modified: trunk/jython/src/org/python/modules/posix/PyStatResult.java =================================================================== --- trunk/jython/src/org/python/modules/posix/PyStatResult.java 2009-10-20 00:06:05 UTC (rev 6877) +++ trunk/jython/src/org/python/modules/posix/PyStatResult.java 2009-10-20 00:20:58 UTC (rev 6878) @@ -1,11 +1,7 @@ /* Copyright (c) Jython Developers */ package org.python.modules.posix; -import org.python.expose.ExposedGet; -import org.python.expose.ExposedMethod; -import org.python.expose.ExposedNew; -import org.python.expose.ExposedType; -import org.python.expose.MethodType; +import org.jruby.ext.posix.FileStat; import org.python.core.ArgParser; import org.python.core.Py; @@ -15,6 +11,12 @@ import org.python.core.PyTuple; import org.python.core.PyType; +import org.python.expose.ExposedGet; +import org.python.expose.ExposedMethod; +import org.python.expose.ExposedNew; +import org.python.expose.ExposedType; +import org.python.expose.MethodType; + @ExposedType(name = "posix.stat_result", isBaseType = false) public class PyStatResult extends PyTuple { @@ -66,6 +68,17 @@ } } + /** + * Return a Python stat result from a posix layer FileStat object. + */ + public static PyStatResult fromFileStat(FileStat stat) { + return new PyStatResult(Py.newInteger(stat.mode()), Py.newLong(stat.ino()), + Py.newLong(stat.dev()), Py.newInteger(stat.nlink()), + Py.newInteger(stat.uid()), Py.newInteger(stat.gid()), + Py.newLong(stat.st_size()), Py.newLong(stat.atime()), + Py.newLong(stat.mtime()), Py.newLong(stat.ctime())); + } + @Override public synchronized PyObject __eq__(PyObject o) { return stat_result___eq__(o); Modified: trunk/jython/src/org/python/modules/posix/PythonPOSIXHandler.java =================================================================== --- trunk/jython/src/org/python/modules/posix/PythonPOSIXHandler.java 2009-10-20 00:06:05 UTC (rev 6877) +++ trunk/jython/src/org/python/modules/posix/PythonPOSIXHandler.java 2009-10-20 00:20:58 UTC (rev 6878) @@ -31,6 +31,10 @@ } public void unimplementedError(String methodName) { + if (methodName.startsWith("stat.")) { + // Ignore unimplemented FileStat methods + return; + } throw Py.NotImplementedError(methodName); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-20 00:06:11
|
Revision: 6877 http://jython.svn.sourceforge.net/jython/?rev=6877&view=rev Author: pjenvey Date: 2009-10-20 00:06:05 +0000 (Tue, 20 Oct 2009) Log Message: ----------- don't hardcode the platform module name Modified Paths: -------------- trunk/jython/Lib/test/test_import_jy.py Modified: trunk/jython/Lib/test/test_import_jy.py =================================================================== --- trunk/jython/Lib/test/test_import_jy.py 2009-10-19 22:08:32 UTC (rev 6876) +++ trunk/jython/Lib/test/test_import_jy.py 2009-10-20 00:06:05 UTC (rev 6877) @@ -100,8 +100,10 @@ def test_override(self): modname = os.path.__name__ tests = [ - ("import os.path" , "('os.path', None, -1, '_posix')" ), - ("import os.path as path2", "('os.path', None, -1, '_posix')" ), + ("import os.path" , "('os.path', None, -1, '_%s')" + % os._name), + ("import os.path as path2", "('os.path', None, -1, '_%s')" + % os._name), ("from os.path import *" , "('os.path', ('*',), -1, '%s')" % modname), ("from os.path import join", This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-19 22:08:41
|
Revision: 6876 http://jython.svn.sourceforge.net/jython/?rev=6876&view=rev Author: pjenvey Date: 2009-10-19 22:08:32 +0000 (Mon, 19 Oct 2009) Log Message: ----------- unused imports Modified Paths: -------------- trunk/jython/src/org/python/modules/posix/OS.java trunk/jython/src/org/python/modules/posix/PosixModule.java Modified: trunk/jython/src/org/python/modules/posix/OS.java =================================================================== --- trunk/jython/src/org/python/modules/posix/OS.java 2009-10-19 22:04:02 UTC (rev 6875) +++ trunk/jython/src/org/python/modules/posix/OS.java 2009-10-19 22:08:32 UTC (rev 6876) @@ -1,9 +1,6 @@ /* Copyright (c) Jython Developers */ package org.python.modules.posix; -import java.lang.reflect.Method; - -import org.python.core.PyObject; import org.python.core.PySystemState; /** Modified: trunk/jython/src/org/python/modules/posix/PosixModule.java =================================================================== --- trunk/jython/src/org/python/modules/posix/PosixModule.java 2009-10-19 22:04:02 UTC (rev 6875) +++ trunk/jython/src/org/python/modules/posix/PosixModule.java 2009-10-19 22:08:32 UTC (rev 6876) @@ -1,14 +1,8 @@ /* Copyright (c) Jython Developers */ package org.python.modules.posix; -import com.kenai.constantine.Constant; import com.kenai.constantine.ConstantSet; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - import org.jruby.ext.posix.JavaPOSIX; import org.jruby.ext.posix.POSIX; import org.jruby.ext.posix.POSIXFactory; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-19 22:04:08
|
Revision: 6875 http://jython.svn.sourceforge.net/jython/?rev=6875&view=rev Author: pjenvey Date: 2009-10-19 22:04:02 +0000 (Mon, 19 Oct 2009) Log Message: ----------- remove the platform hiding functionality, until we actually need it Modified Paths: -------------- trunk/jython/src/org/python/modules/posix/OS.java trunk/jython/src/org/python/modules/posix/PosixModule.java Modified: trunk/jython/src/org/python/modules/posix/OS.java =================================================================== --- trunk/jython/src/org/python/modules/posix/OS.java 2009-10-19 22:02:41 UTC (rev 6874) +++ trunk/jython/src/org/python/modules/posix/OS.java 2009-10-19 22:04:02 UTC (rev 6875) @@ -41,37 +41,6 @@ } /** - * Hide module level functions defined in the PosixModule dict not applicable to this - * OS, identified by the PosixModule.Hide annotation. - * - * @param dict The PosixModule module dict - */ - void hideFunctions(PyObject dict) { - for (Method method: PosixModule.class.getDeclaredMethods()) { - if (isHidden(method)) { - dict.__setitem__(method.getName(), null); - } - } - } - - /** - * Determine if method should be hidden for this OS. - * - * @param method a PosixModule Method - * @return true if should be hidden - */ - private boolean isHidden(Method method) { - if (method.isAnnotationPresent(PosixModule.Hide.class)) { - for (OS os : method.getAnnotation(PosixModule.Hide.class).value()) { - if (os == this) { - return true; - } - } - } - return false; - } - - /** * Return the OS we're running on. */ static OS getOS() { Modified: trunk/jython/src/org/python/modules/posix/PosixModule.java =================================================================== --- trunk/jython/src/org/python/modules/posix/PosixModule.java 2009-10-19 22:02:41 UTC (rev 6874) +++ trunk/jython/src/org/python/modules/posix/PosixModule.java 2009-10-19 22:04:02 UTC (rev 6875) @@ -68,9 +68,6 @@ dict.__setitem__("_posix_impl", Py.java2py(posix)); dict.__setitem__("_native_posix", Py.newBoolean(!(posix instanceof JavaPOSIX))); - // Hide functions not applicable to this platform - os.hideFunctions(dict); - // Hide from Python dict.__setitem__("classDictInit", null); dict.__setitem__("getPOSIX", null); @@ -106,10 +103,4 @@ public static String getOSName() { return os.getModuleName(); } - - @Retention(RetentionPolicy.RUNTIME) - @Target(ElementType.METHOD) - @interface Hide { - OS[] value(); - } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-19 22:02:54
|
Revision: 6874 http://jython.svn.sourceforge.net/jython/?rev=6874&view=rev Author: pjenvey Date: 2009-10-19 22:02:41 +0000 (Mon, 19 Oct 2009) Log Message: ----------- o pull posix bits out of os into their own module o further pull some of the slower to initialize bits out of posix into a Java _posix (_nt on Windows) module. this speeds up startup. eventually we should move more if not everything there o adapt 2.6's os.py: - hide exec* - we don't need to use set/get/putenv for the environ dict wrapper - our stat_result can be pickled, remove the copy_reg workaround - re-add some 2.5isms Modified Paths: -------------- trunk/jython/CoreExposed.includes trunk/jython/Lib/grp.py trunk/jython/Lib/os.py trunk/jython/Lib/posix.py trunk/jython/Lib/pwd.py trunk/jython/Lib/select.py trunk/jython/Lib/subprocess.py trunk/jython/Lib/test/test_import_jy.py trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/io/FileIO.java trunk/jython/src/org/python/core/io/StreamIO.java trunk/jython/src/org/python/core/util/FileUtil.java trunk/jython/src/org/python/modules/Setup.java trunk/jython/src/org/python/util/jython.java Added Paths: ----------- trunk/jython/Lib/nt.py trunk/jython/src/org/python/modules/posix/ trunk/jython/src/org/python/modules/posix/OS.java trunk/jython/src/org/python/modules/posix/PosixModule.java trunk/jython/src/org/python/modules/posix/PyStatResult.java trunk/jython/src/org/python/modules/posix/PythonPOSIXHandler.java Modified: trunk/jython/CoreExposed.includes =================================================================== --- trunk/jython/CoreExposed.includes 2009-10-19 21:56:07 UTC (rev 6873) +++ trunk/jython/CoreExposed.includes 2009-10-19 22:02:41 UTC (rev 6874) @@ -61,6 +61,7 @@ org/python/modules/_weakref/ReferenceType.class org/python/modules/operator$PyAttrGetter.class org/python/modules/operator$PyItemGetter.class +org/python/modules/posix/PyStatResult.class org/python/modules/random/PyRandom.class org/python/modules/thread/PyLocal.class org/python/modules/time/PyTimeTuple.class Modified: trunk/jython/Lib/grp.py =================================================================== --- trunk/jython/Lib/grp.py 2009-10-19 21:56:07 UTC (rev 6873) +++ trunk/jython/Lib/grp.py 2009-10-19 22:02:41 UTC (rev 6874) @@ -17,7 +17,7 @@ __all__ = ['getgrgid', 'getgrnam', 'getgrall'] -from os import _name, _posix +from os import _name, _posix_impl if _name == 'nt': raise ImportError, 'grp module not supported on Windows' @@ -50,7 +50,7 @@ Return the group database entry for the given numeric group ID. If id is not valid, raise KeyError. """ - entry = _posix.getgrgid(uid) + entry = _posix_impl.getgrgid(uid) if not entry: raise KeyError(uid) return struct_group(entry) @@ -62,7 +62,7 @@ Return the group database entry for the given group name. If name is not valid, raise KeyError. """ - entry = _posix.getgrnam(name) + entry = _posix_impl.getgrnam(name) if not entry: raise KeyError(name) return struct_group(entry) @@ -76,7 +76,7 @@ """ groups = [] while True: - group = _posix.getgrent() + group = _posix_impl.getgrent() if not group: break groups.append(struct_group(group)) Added: trunk/jython/Lib/nt.py =================================================================== --- trunk/jython/Lib/nt.py (rev 0) +++ trunk/jython/Lib/nt.py 2009-10-19 22:02:41 UTC (rev 6874) @@ -0,0 +1,2 @@ +from posix import __all__ +from posix import * Modified: trunk/jython/Lib/os.py =================================================================== --- trunk/jython/Lib/os.py 2009-10-19 21:56:07 UTC (rev 6873) +++ trunk/jython/Lib/os.py 2009-10-19 22:02:41 UTC (rev 6874) @@ -38,8 +38,9 @@ except AttributeError: return [n for n in dir(module) if n[0] != '_'] -if 'posix' in _names: - name = 'posix' +name = 'java' +if '_posix' in _names: + _name = 'posix' linesep = '\n' from posix import * try: @@ -52,8 +53,8 @@ __all__.extend(_get_exports_list(posix)) del posix -elif 'nt' in _names: - name = 'nt' +elif '_nt' in _names: + _name = 'nt' linesep = '\r\n' from nt import * try: @@ -66,8 +67,8 @@ __all__.extend(_get_exports_list(nt)) del nt -elif 'os2' in _names: - name = 'os2' +elif '_os2' in _names: + _name = 'os2' linesep = '\r\n' from os2 import * try: @@ -84,8 +85,8 @@ __all__.extend(_get_exports_list(os2)) del os2 -elif 'ce' in _names: - name = 'ce' +elif '_ce' in _names: + _name = 'ce' linesep = '\r\n' from ce import * try: @@ -99,8 +100,8 @@ __all__.extend(_get_exports_list(ce)) del ce -elif 'riscos' in _names: - name = 'riscos' +elif '_riscos' in _names: + _name = 'riscos' linesep = '\n' from riscos import * try: @@ -304,90 +305,97 @@ except NameError: environ = {} -def execl(file, *args): - """execl(file, *args) +def _exists(name): + # CPython eval's the name, whereas looking in __all__ works for + # Jython and is much faster + return name in __all__ - Execute the executable file with argument list args, replacing the - current process. """ - execv(file, args) +if _exists('execv'): -def execle(file, *args): - """execle(file, *args, env) + def execl(file, *args): + """execl(file, *args) - Execute the executable file with argument list args and - environment env, replacing the current process. """ - env = args[-1] - execve(file, args[:-1], env) + Execute the executable file with argument list args, replacing the + current process. """ + execv(file, args) -def execlp(file, *args): - """execlp(file, *args) + def execle(file, *args): + """execle(file, *args, env) - Execute the executable file (which is searched for along $PATH) - with argument list args, replacing the current process. """ - execvp(file, args) + Execute the executable file with argument list args and + environment env, replacing the current process. """ + env = args[-1] + execve(file, args[:-1], env) -def execlpe(file, *args): - """execlpe(file, *args, env) + def execlp(file, *args): + """execlp(file, *args) - Execute the executable file (which is searched for along $PATH) - with argument list args and environment env, replacing the current - process. """ - env = args[-1] - execvpe(file, args[:-1], env) + Execute the executable file (which is searched for along $PATH) + with argument list args, replacing the current process. """ + execvp(file, args) -def execvp(file, args): - """execp(file, args) + def execlpe(file, *args): + """execlpe(file, *args, env) - Execute the executable file (which is searched for along $PATH) - with argument list args, replacing the current process. - args may be a list or tuple of strings. """ - _execvpe(file, args) + Execute the executable file (which is searched for along $PATH) + with argument list args and environment env, replacing the current + process. """ + env = args[-1] + execvpe(file, args[:-1], env) -def execvpe(file, args, env): - """execvpe(file, args, env) + def execvp(file, args): + """execp(file, args) - Execute the executable file (which is searched for along $PATH) - with argument list args and environment env , replacing the - current process. - args may be a list or tuple of strings. """ - _execvpe(file, args, env) + Execute the executable file (which is searched for along $PATH) + with argument list args, replacing the current process. + args may be a list or tuple of strings. """ + _execvpe(file, args) -__all__.extend(["execl","execle","execlp","execlpe","execvp","execvpe"]) + def execvpe(file, args, env): + """execvpe(file, args, env) -def _execvpe(file, args, env=None): - if env is not None: - func = execve - argrest = (args, env) - else: - func = execv - argrest = (args,) - env = environ + Execute the executable file (which is searched for along $PATH) + with argument list args and environment env , replacing the + current process. + args may be a list or tuple of strings. """ + _execvpe(file, args, env) - head, tail = path.split(file) - if head: - func(file, *argrest) - return - if 'PATH' in env: - envpath = env['PATH'] - else: - envpath = defpath - PATH = envpath.split(pathsep) - saved_exc = None - saved_tb = None - for dir in PATH: - fullname = path.join(dir, file) - try: - func(fullname, *argrest) - except error, e: - tb = sys.exc_info()[2] - if (e.errno != errno.ENOENT and e.errno != errno.ENOTDIR - and saved_exc is None): - saved_exc = e - saved_tb = tb - if saved_exc: - raise error, saved_exc, saved_tb - raise error, e, tb + __all__.extend(["execl","execle","execlp","execlpe","execvp","execvpe"]) + def _execvpe(file, args, env=None): + if env is not None: + func = execve + argrest = (args, env) + else: + func = execv + argrest = (args,) + env = environ + + head, tail = path.split(file) + if head: + func(file, *argrest) + return + if 'PATH' in env: + envpath = env['PATH'] + else: + envpath = defpath + PATH = envpath.split(pathsep) + saved_exc = None + saved_tb = None + for dir in PATH: + fullname = path.join(dir, file) + try: + func(fullname, *argrest) + except error, e: + tb = sys.exc_info()[2] + if (e.errno != errno.ENOENT and e.errno != errno.ENOTDIR + and saved_exc is None): + saved_exc = e + saved_tb = tb + if saved_exc: + raise error, saved_exc, saved_tb + raise error, e, tb + # Change environ to automatically call putenv() if it exists try: # This will fail if there's no putenv @@ -405,10 +413,10 @@ def unsetenv(key): putenv(key, "") - if name == "riscos": + if _name == "riscos": # On RISC OS, all env access goes through getenv and putenv from riscosenviron import _Environ - elif name in ('os2', 'nt'): # Where Env Var Names Must Be UPPERCASE + elif _name in ('os2', 'nt'): # Where Env Var Names Must Be UPPERCASE # But we store them as upper case class _Environ(UserDict.IterableUserDict): def __init__(self, environ): @@ -417,26 +425,11 @@ for k, v in environ.items(): data[k.upper()] = v def __setitem__(self, key, item): - putenv(key, item) self.data[key.upper()] = item def __getitem__(self, key): return self.data[key.upper()] - try: - unsetenv - except NameError: - def __delitem__(self, key): - del self.data[key.upper()] - else: - def __delitem__(self, key): - unsetenv(key) - del self.data[key.upper()] - def clear(self): - for key in self.data.keys(): - unsetenv(key) - del self.data[key] - def pop(self, key, *args): - unsetenv(key) - return self.data.pop(key.upper(), *args) + def __delitem__(self, key): + del self.data[key.upper()] def has_key(self, key): return key.upper() in self.data def __contains__(self, key): @@ -462,64 +455,14 @@ def copy(self): return dict(self) - else: # Where Env Var Names Can Be Mixed Case - class _Environ(UserDict.IterableUserDict): - def __init__(self, environ): - UserDict.UserDict.__init__(self) - self.data = environ - def __setitem__(self, key, item): - putenv(key, item) - self.data[key] = item - def update(self, dict=None, **kwargs): - if dict: - try: - keys = dict.keys() - except AttributeError: - # List of (key, value) - for k, v in dict: - self[k] = v - else: - # got keys - # cannot use items(), since mappings - # may not have them. - for k in keys: - self[k] = dict[k] - if kwargs: - self.update(kwargs) - try: - unsetenv - except NameError: - pass - else: - def __delitem__(self, key): - unsetenv(key) - del self.data[key] - def clear(self): - for key in self.data.keys(): - unsetenv(key) - del self.data[key] - def pop(self, key, *args): - unsetenv(key) - return self.data.pop(key, *args) - def copy(self): - return dict(self) + environ = _Environ(environ) - - environ = _Environ(environ) - def getenv(key, default=None): """Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default.""" return environ.get(key, default) __all__.append("getenv") -def _exists(name): - try: - eval(name) - return True - except NameError: - return False - # Supply spawn*() (probably only for Unix) if _exists("fork") and not _exists("spawnv") and _exists("execv"): @@ -655,7 +598,7 @@ # Supply popen2 etc. (for Unix) -if _exists("fork"): +if sys.platform.startswith('java') or _exists("fork"): if not _exists("popen2"): def popen2(cmd, mode="t", bufsize=-1): """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' @@ -664,10 +607,6 @@ is a string it will be passed to the shell (as with os.system()). If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdin, child_stdout) are returned.""" - import warnings - msg = "os.popen2 is deprecated. Use the subprocess module." - warnings.warn(msg, DeprecationWarning, stacklevel=2) - import subprocess PIPE = subprocess.PIPE p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring), @@ -684,10 +623,6 @@ is a string it will be passed to the shell (as with os.system()). If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdin, child_stdout, child_stderr) are returned.""" - import warnings - msg = "os.popen3 is deprecated. Use the subprocess module." - warnings.warn(msg, DeprecationWarning, stacklevel=2) - import subprocess PIPE = subprocess.PIPE p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring), @@ -704,10 +639,6 @@ is a string it will be passed to the shell (as with os.system()). If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdin, child_stdout_stderr) are returned.""" - import warnings - msg = "os.popen4 is deprecated. Use the subprocess module." - warnings.warn(msg, DeprecationWarning, stacklevel=2) - import subprocess PIPE = subprocess.PIPE p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring), @@ -716,33 +647,6 @@ return p.stdin, p.stdout __all__.append("popen4") -import copy_reg as _copy_reg - -def _make_stat_result(tup, dict): - return stat_result(tup, dict) - -def _pickle_stat_result(sr): - (type, args) = sr.__reduce__() - return (_make_stat_result, args) - -try: - _copy_reg.pickle(stat_result, _pickle_stat_result, _make_stat_result) -except NameError: # stat_result may not exist - pass - -def _make_statvfs_result(tup, dict): - return statvfs_result(tup, dict) - -def _pickle_statvfs_result(sr): - (type, args) = sr.__reduce__() - return (_make_statvfs_result, args) - -try: - _copy_reg.pickle(statvfs_result, _pickle_statvfs_result, - _make_statvfs_result) -except NameError: # statvfs_result may not exist - pass - if not _exists("urandom"): def urandom(n): """urandom(n) -> str @@ -754,10 +658,8 @@ _urandomfd = open("/dev/urandom", O_RDONLY) except (OSError, IOError): raise NotImplementedError("/dev/urandom (or equivalent) not found") - try: - bs = b"" - while n - len(bs) >= 1: - bs += read(_urandomfd, n - len(bs)) - finally: - close(_urandomfd) - return bs + bytes = "" + while len(bytes) < n: + bytes += read(_urandomfd, n - len(bytes)) + close(_urandomfd) + return bytes Modified: trunk/jython/Lib/posix.py =================================================================== --- trunk/jython/Lib/posix.py 2009-10-19 21:56:07 UTC (rev 6873) +++ trunk/jython/Lib/posix.py 2009-10-19 22:02:41 UTC (rev 6874) @@ -1,235 +1,47 @@ -r"""OS routines for Java, with some attempts to support NT, and Posix -functionality. - -This exports: - - all functions from posix, nt, dos, os2, mac, or ce, e.g. unlink, stat, etc. - - os.path is one of the modules posixpath, ntpath, macpath, or dospath - - os.name is 'posix', 'nt', 'dos', 'os2', 'mac', 'ce' or 'riscos' - - os.curdir is a string representing the current directory ('.' or ':') - - os.pardir is a string representing the parent directory ('..' or '::') - - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\') - - os.altsep is the alternate pathname separator (None or '/') - - os.pathsep is the component separator used in $PATH etc - - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n') - - os.defpath is the default search path for executables - -Programs that import and use 'os' stand a better chance of being -portable between different platforms. Of course, they must then -only use functions that are defined by all platforms (e.g., unlink -and opendir), and leave all pathname manipulation to os.path -(e.g., split and join). """ - -# CPython os.py __all__ -__all__ = ["altsep", "curdir", "pardir", "sep", "pathsep", "linesep", - "defpath", "name", "path", - "SEEK_SET", "SEEK_CUR", "SEEK_END"] - -# Would come from the posix/nt/etc. modules on CPython -__all__.extend(['EX_OK', 'F_OK', 'O_APPEND', 'O_CREAT', 'O_EXCL', 'O_RDONLY', - 'O_RDWR', 'O_SYNC', 'O_TRUNC', 'O_WRONLY', 'R_OK', 'SEEK_CUR', - 'SEEK_END', 'SEEK_SET', 'W_OK', 'X_OK', '_exit', 'access', - 'altsep', 'chdir', 'chmod', 'close', 'curdir', 'defpath', - 'environ', 'error', 'fdopen', 'fsync', 'getcwd', 'getcwdu', - 'getenv', 'getpid', 'isatty', 'linesep', 'listdir', 'lseek', - 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', - 'pathsep', 'popen', 'popen2', 'popen3', 'popen4', 'putenv', - 'read', 'remove', 'removedirs', 'rename', 'renames', 'rmdir', - 'sep', 'stat', 'stat_result', 'strerror', 'system', 'unlink', - 'unsetenv', 'utime', 'walk', 'write']) - +This module provides access to operating system functionality that is +standardized by the C Standard and the POSIX standard (a thinly +disguised Unix interface). Refer to the library manual and +corresponding Unix manual entries for more information on calls. +""" +try: + import _posix + from _posix import * +except: + import _nt as _posix + from _nt import * import errno import jarray import java.lang.System -import time import stat as _stat import sys from java.io import File from org.python.core.io import FileDescriptors, FileIO, IOBase from org.python.core.Py import newString as asPyString - try: from org.python.constantine.platform import Errno except ImportError: from com.kenai.constantine.platform import Errno -# Mapping of: os._name: [name list, shell command list] -_os_map = dict(nt=[ - ['Windows'], - [['cmd.exe', '/c'], ['command.com', '/c']] - ], - posix=[ - [], # posix is a fallback, instead of matching names - [['/bin/sh', '-c']] - ] - ) +__all__ = _posix.__all__[:] +__all__.extend(['_exit', 'access', 'chdir', 'chmod', 'close', 'environ', + 'fdopen', 'fsync', 'ftruncate', 'getcwd', 'getcwdu', 'getenv', + 'getpid', 'isatty', 'listdir', 'lseek', 'lstat', 'mkdir', + 'open', 'popen', 'putenv', 'read', 'remove', 'rename', 'rmdir', + 'stat', 'strerror', 'system', 'umask', 'unlink', 'unsetenv', + 'urandom', 'utime', 'write']) -def get_os_type(): - """Return the name of the type of the underlying OS. +_name = _posix.__name__[1:] - Returns a value suitable for the os.name variable (though not - necessarily intended to be for os.name Jython). This value may be - overwritten in the Jython registry. - """ - os_name = sys.registry.getProperty('python.os') - if os_name: - return asPyString(os_name) - - os_name = asPyString(java.lang.System.getProperty('os.name')) - os_type = None - for type, (patterns, shell_commands) in _os_map.iteritems(): - for pattern in patterns: - if os_name.startswith(pattern): - # determine the shell_command later, when it's needed: - # it requires os.path (which isn't setup yet) - return type - return 'posix' - -name = 'java' -# WARNING: _name is private: for Jython internal usage only! user code -# should *NOT* use it -_name = get_os_type() - -try: - from org.python.posix import JavaPOSIX, POSIXHandler, POSIXFactory -except ImportError: - from org.jruby.ext.posix import JavaPOSIX, POSIXHandler, POSIXFactory - -class PythonPOSIXHandler(POSIXHandler): - def error(self, error, msg): - err = getattr(errno, error.name(), None) - if err is None: - raise OSError('%s: %s' % (error, asPyString(msg))) - raise OSError(err, strerror(err), asPyString(msg)) - def unimplementedError(self, method_name): - raise NotImplementedError(method_name) - def warn(self, warning_id, msg, rest): - pass # XXX implement - def isVerbose(self): - return False - def getCurrentWorkingDirectory(self): - return File(getcwdu()) - def getEnv(self): - return ['%s=%s' % (key, val) for key, val in environ.iteritems()] - def getInputStream(self): - return getattr(java.lang.System, 'in') # XXX handle resetting - def getOutputStream(self): - return java.lang.System.out # XXX handle resetting - def getPID(self): - return 0 - def getErrorStream(self): - return java.lang.System.err # XXX handle resetting - -_posix = POSIXFactory.getPOSIX(PythonPOSIXHandler(), True) -_native_posix = not isinstance(_posix, JavaPOSIX) - -if _name == 'nt': - import ntpath as path -else: - import posixpath as path - -sys.modules['os.path'] = _path = path -from os.path import curdir, pardir, sep, pathsep, defpath, extsep, altsep, devnull -linesep = java.lang.System.getProperty('line.separator') - -# open for reading only -O_RDONLY = 0x0 -# open for writing only -O_WRONLY = 0x1 -# open for reading and writing -O_RDWR = 0x2 - -# set append mode -O_APPEND = 0x8 -# synchronous writes -O_SYNC = 0x80 - -# create if nonexistant -O_CREAT = 0x200 -# truncate to zero length -O_TRUNC = 0x400 -# error if already exists -O_EXCL = 0x800 - -# seek variables -SEEK_SET = 0 -SEEK_CUR = 1 -SEEK_END = 2 - -# test for existence of file -F_OK = 0 -# test for execute or search permission -X_OK = 1<<0 -# test for write permission -W_OK = 1<<1 -# test for read permission -R_OK = 1<<2 - -# successful termination -EX_OK = 0 - # Java class representing the size of a time_t. internal use, lazily set _time_t = None -class stat_result: +# For urandom +urandom_source = None - _stat_members = ( - ('st_mode', _stat.ST_MODE), - ('st_ino', _stat.ST_INO), - ('st_dev', _stat.ST_DEV), - ('st_nlink', _stat.ST_NLINK), - ('st_uid', _stat.ST_UID), - ('st_gid', _stat.ST_GID), - ('st_size', _stat.ST_SIZE), - ('st_atime', _stat.ST_ATIME), - ('st_mtime', _stat.ST_MTIME), - ('st_ctime', _stat.ST_CTIME), - ) +# Lazily loaded path module +_path = None - def __init__(self, results): - if len(results) != 10: - raise TypeError("stat_result() takes an a 10-sequence") - for (name, index) in stat_result._stat_members: - self.__dict__[name] = results[index] - - @classmethod - def from_jnastat(cls, s): - results = [] - for meth in (s.mode, s.ino, s.dev, s.nlink, s.uid, s.gid, s.st_size, - s.atime, s.mtime, s.ctime): - try: - results.append(meth()) - except NotImplementedError: - results.append(0) - return cls(results) - - def __getitem__(self, i): - if i < 0 or i > 9: - raise IndexError(i) - return getattr(self, stat_result._stat_members[i][0]) - - def __setitem__(self, x, value): - raise TypeError("object doesn't support item assignment") - - def __setattr__(self, name, value): - if name in [x[0] for x in stat_result._stat_members]: - raise TypeError(name) - raise AttributeError("readonly attribute") - - def __len__(self): - return 10 - - def __cmp__(self, other): - if not isinstance(other, stat_result): - return 1 - return cmp(self.__dict__, other.__dict__) - - def __repr__(self): - return repr(tuple(self.__dict__[member[0]] for member - in stat_result._stat_members)) - -error = OSError - def _exit(n=0): """_exit(status) @@ -257,12 +69,13 @@ Change the current working directory to the specified path. """ - realpath = _path.realpath(path) - if not _path.exists(realpath): - raise OSError(errno.ENOENT, strerror(errno.ENOENT), path) - if not _path.isdir(realpath): + global _path + if not _stat.S_ISDIR(stat(path).st_mode): raise OSError(errno.ENOTDIR, strerror(errno.ENOTDIR), path) - sys.setCurrentWorkingDir(realpath) + if _path is None: + import os + _path = os.path + sys.setCurrentWorkingDir(_path.realpath(path)) def listdir(path): """listdir(path) -> list_of_strings @@ -289,7 +102,7 @@ abs_path = sys.getPath(path) if not File(abs_path).exists(): raise OSError(errno.ENOENT, strerror(errno.ENOENT), path) - _posix.chmod(abs_path, mode) + _posix_impl.chmod(abs_path, mode) def mkdir(path, mode='ignored'): """mkdir(path [, mode=0777]) @@ -298,7 +111,7 @@ The optional parameter is currently ignored. """ - # XXX: use _posix.mkdir when we can get the real errno upon failure + # XXX: use _posix_impl.mkdir when we can get the real errno upon failure fp = File(sys.getPath(path)) if not fp.mkdir(): if fp.isDirectory() or fp.isFile(): @@ -308,31 +121,6 @@ msg = strerror(err) if err else "couldn't make directory" raise OSError(err, msg, path) -def makedirs(path, mode='ignored'): - """makedirs(path [, mode=0777]) - - Super-mkdir; create a leaf directory and all intermediate ones. - - Works like mkdir, except that any intermediate path segment (not - just the rightmost) will be created if it does not exist. - The optional parameter is currently ignored. - """ - sys_path = sys.getPath(path) - if File(sys_path).mkdirs(): - return - - # if making a /x/y/z/., java.io.File#mkdirs inexplicably fails. So we need - # to force it - - # need to use _path instead of path, because param is hiding - # os.path module in namespace! - head, tail = _path.split(sys_path) - if tail == curdir: - if File(_path.join(head)).mkdirs(): - return - - raise OSError(0, "couldn't make directories", path) - def remove(path): """remove(path) @@ -351,33 +139,6 @@ if not File(sys.getPath(path)).renameTo(File(sys.getPath(newpath))): raise OSError(0, "couldn't rename file", path) -#XXX: copied from CPython 2.5.1 -def renames(old, new): - """renames(old, new) - - Super-rename; create directories as necessary and delete any left - empty. Works like rename, except creation of any intermediate - directories needed to make the new pathname good is attempted - first. After the rename, directories corresponding to rightmost - path segments of the old name will be pruned way until either the - whole path is consumed or a nonempty directory is found. - - Note: this function can fail with the new directory structure made - if you lack permissions needed to unlink the leaf directory or - file. - - """ - head, tail = path.split(new) - if head and tail and not path.exists(head): - makedirs(head) - rename(old, new) - head, tail = path.split(old) - if head and tail: - try: - removedirs(head) - except error: - pass - def rmdir(path): """rmdir(path) @@ -390,31 +151,6 @@ elif not f.delete(): raise OSError(0, "couldn't delete directory", path) -#XXX: copied from CPython 2.5.1 -def removedirs(name): - """removedirs(path) - - Super-rmdir; remove a leaf directory and empty all intermediate - ones. Works like rmdir except that, if the leaf directory is - successfully removed, directories corresponding to rightmost path - segments will be pruned away until either the whole path is - consumed or an error occurs. Errors during this latter phase are - ignored -- they generally mean that a directory was not empty. - - """ - rmdir(name) - head, tail = path.split(name) - if not tail: - head, tail = path.split(head) - while head and tail: - try: - rmdir(head) - except error: - break - head, tail = path.split(head) - -__all__.extend(['makedirs', 'renames', 'removedirs']) - def strerror(code): """strerror(code) -> string @@ -475,7 +211,7 @@ """ abs_path = sys.getPath(path) try: - return stat_result.from_jnastat(_posix.stat(abs_path)) + return _from_jnastat(_posix_impl.stat(abs_path)) except NotImplementedError: pass f = File(abs_path) @@ -501,7 +237,7 @@ """ abs_path = sys.getPath(path) try: - return stat_result.from_jnastat(_posix.lstat(abs_path)) + return _from_jnastat(_posix_impl.lstat(abs_path)) except NotImplementedError: pass f = File(sys.getPath(path)) @@ -524,7 +260,7 @@ # The parent directory's path is not canonical (one of the parent # directories is a symlink). Build a new path with the parent's # canonical path and compare the files - f = File(_path.join(can_parent.getAbsolutePath(), f.getName())) + f = File(can_parent.getAbsolutePath(), f.getName()) if f.getAbsolutePath() != f.getCanonicalPath(): return stat_result((_stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0)) @@ -556,7 +292,7 @@ else: raise TypeError('utime() arg 2 must be a tuple (atime, mtime)') - _posix.utimes(path, atimeval, mtimeval) + _posix_impl.utimes(path, atimeval, mtimeval) def _to_timeval(seconds): """Convert seconds (with a fraction) from epoch to a 2 item tuple of @@ -647,8 +383,9 @@ if updating and writing: raise OSError(errno.EINVAL, strerror(errno.EINVAL), filename) - if not creating and not path.exists(filename): - raise OSError(errno.ENOENT, strerror(errno.ENOENT), filename) + if not creating: + # raises ENOENT if it doesn't exist + stat(filename) if not writing: if updating: @@ -678,7 +415,8 @@ try: fchannel = RandomAccessFile(sys.getPath(filename), 'rws').getChannel() except FileNotFoundException, fnfe: - if path.isdir(filename): + #if path.isdir(filename): + if _stat.S_ISDIR(stat(filename).st_mode): raise OSError(errno.EISDIR, strerror(errno.EISDIR)) raise OSError(errno.ENOENT, strerror(errno.ENOENT), filename) return FileIO(fchannel, mode) @@ -757,51 +495,6 @@ def __iter__(self): return iter(self._stream) -# os module versions of the popen# methods have different return value -# order than popen2 functions - -def popen2(cmd, mode="t", bufsize=-1): - """Execute the shell command cmd in a sub-process. - - On UNIX, 'cmd' may be a sequence, in which case arguments will be - passed directly to the program without shell intervention (as with - os.spawnv()). If 'cmd' is a string it will be passed to the shell - (as with os.system()). If 'bufsize' is specified, it sets the - buffer size for the I/O pipes. The file objects (child_stdin, - child_stdout) are returned. - """ - import popen2 - stdout, stdin = popen2.popen2(cmd, bufsize) - return stdin, stdout - -def popen3(cmd, mode="t", bufsize=-1): - """Execute the shell command 'cmd' in a sub-process. - - On UNIX, 'cmd' may be a sequence, in which case arguments will be - passed directly to the program without shell intervention - (as with os.spawnv()). If 'cmd' is a string it will be passed - to the shell (as with os.system()). If 'bufsize' is specified, - it sets the buffer size for the I/O pipes. The file objects - (child_stdin, child_stdout, child_stderr) are returned. - """ - import popen2 - stdout, stdin, stderr = popen2.popen3(cmd, bufsize) - return stdin, stdout, stderr - -def popen4(cmd, mode="t", bufsize=-1): - """Execute the shell command 'cmd' in a sub-process. - - On UNIX, 'cmd' may be a sequence, in which case arguments will be - passed directly to the program without shell intervention - (as with os.spawnv()). If 'cmd' is a string it will be passed - to the shell (as with os.system()). If 'bufsize' is specified, - it sets the buffer size for the I/O pipes. The file objects - (child_stdin, child_stdout_stderr) are returned. - """ - import popen2 - stdout, stdin = popen2.popen4(cmd, bufsize) - return stdin, stdout - def getlogin(): """getlogin() -> string @@ -809,139 +502,8 @@ """ return java.lang.System.getProperty("user.name") -#XXX: copied from CPython's release23-maint branch revision 56502 -def walk(top, topdown=True, onerror=None): - """Directory tree generator. - - For each directory in the directory tree rooted at top (including top - itself, but excluding '.' and '..'), yields a 3-tuple - - dirpath, dirnames, filenames - - dirpath is a string, the path to the directory. dirnames is a list of - the names of the subdirectories in dirpath (excluding '.' and '..'). - filenames is a list of the names of the non-directory files in dirpath. - Note that the names in the lists are just names, with no path components. - To get a full path (which begins with top) to a file or directory in - dirpath, do os.path.join(dirpath, name). - - If optional arg 'topdown' is true or not specified, the triple for a - directory is generated before the triples for any of its subdirectories - (directories are generated top down). If topdown is false, the triple - for a directory is generated after the triples for all of its - subdirectories (directories are generated bottom up). - - When topdown is true, the caller can modify the dirnames list in-place - (e.g., via del or slice assignment), and walk will only recurse into the - subdirectories whose names remain in dirnames; this can be used to prune - the search, or to impose a specific order of visiting. Modifying - dirnames when topdown is false is ineffective, since the directories in - dirnames have already been generated by the time dirnames itself is - generated. - - By default errors from the os.listdir() call are ignored. If - optional arg 'onerror' is specified, it should be a function; it - will be called with one argument, an os.error instance. It can - report the error to continue with the walk, or raise the exception - to abort the walk. Note that the filename is available as the - filename attribute of the exception object. - - Caution: if you pass a relative pathname for top, don't change the - current working directory between resumptions of walk. walk never - changes the current directory, and assumes that the client doesn't - either. - - Example: - - from os.path import join, getsize - for root, dirs, files in walk('python/Lib/email'): - print root, "consumes", - print sum([getsize(join(root, name)) for name in files]), - print "bytes in", len(files), "non-directory files" - if 'CVS' in dirs: - dirs.remove('CVS') # don't visit CVS directories - """ - - from os.path import join, isdir, islink - - # We may not have read permission for top, in which case we can't - # get a list of the files the directory contains. os.path.walk - # always suppressed the exception then, rather than blow up for a - # minor reason when (say) a thousand readable directories are still - # left to visit. That logic is copied here. - try: - # Note that listdir and error are globals in this module due - # to earlier import-*. - names = listdir(top) - except error, err: - if onerror is not None: - onerror(err) - return - - dirs, nondirs = [], [] - for name in names: - if isdir(join(top, name)): - dirs.append(name) - else: - nondirs.append(name) - - if topdown: - yield top, dirs, nondirs - for name in dirs: - path = join(top, name) - if not islink(path): - for x in walk(path, topdown, onerror): - yield x - if not topdown: - yield top, dirs, nondirs - -__all__.append("walk") - environ = sys.getEnviron() -if _name in ('os2', 'nt'): # Where Env Var Names Must Be UPPERCASE - import UserDict - - # But we store them as upper case - class _Environ(UserDict.IterableUserDict): - def __init__(self, environ): - UserDict.UserDict.__init__(self) - data = self.data - for k, v in environ.items(): - data[k.upper()] = v - def __setitem__(self, key, item): - self.data[key.upper()] = item - def __getitem__(self, key): - return self.data[key.upper()] - def __delitem__(self, key): - del self.data[key.upper()] - def has_key(self, key): - return key.upper() in self.data - def __contains__(self, key): - return key.upper() in self.data - def get(self, key, failobj=None): - return self.data.get(key.upper(), failobj) - def update(self, dict=None, **kwargs): - if dict: - try: - keys = dict.keys() - except AttributeError: - # List of (key, value) - for k, v in dict: - self[k] = v - else: - # got keys - # cannot use items(), since mappings - # may not have them. - for k in keys: - self[k] = dict[k] - if kwargs: - self.update(kwargs) - def copy(self): - return dict(self) - - environ = _Environ(environ) - def putenv(key, value): """putenv(key, value) @@ -968,14 +530,14 @@ Create a hard link to a file. """ - _posix.link(sys.getPath(src), sys.getPath(dst)) + _posix_impl.link(sys.getPath(src), sys.getPath(dst)) def symlink(src, dst): """symlink(src, dst) Create a symbolic link pointing to src named dst. """ - _posix.symlink(src, sys.getPath(dst)) + _posix_impl.symlink(src, sys.getPath(dst)) def readlink(path): """readlink(path) -> path @@ -983,61 +545,61 @@ Return a string representing the path to which the symbolic link points. """ - return _posix.readlink(sys.getPath(path)) + return _posix_impl.readlink(sys.getPath(path)) def getegid(): """getegid() -> egid Return the current process's effective group id.""" - return _posix.getegid() + return _posix_impl.getegid() def geteuid(): """geteuid() -> euid Return the current process's effective user id.""" - return _posix.geteuid() + return _posix_impl.geteuid() def getgid(): """getgid() -> gid Return the current process's group id.""" - return _posix.getgid() + return _posix_impl.getgid() def getlogin(): """getlogin() -> string Return the actual login name.""" - return _posix.getlogin() + return _posix_impl.getlogin() def getpgrp(): """getpgrp() -> pgrp Return the current process group id.""" - return _posix.getpgrp() + return _posix_impl.getpgrp() def getppid(): """getppid() -> ppid Return the parent's process id.""" - return _posix.getppid() + return _posix_impl.getppid() def getuid(): """getuid() -> uid Return the current process's user id.""" - return _posix.getuid() + return _posix_impl.getuid() def setpgrp(): """setpgrp() Make this process a session leader.""" - return _posix.setpgrp() + return _posix_impl.setpgrp() def setsid(): """setsid() Call the system call setsid().""" - return _posix.setsid() + return _posix_impl.setsid() # This implementation of fork partially works on # Jython. Diagnosing what works, what doesn't, and fixing it is @@ -1049,13 +611,13 @@ # # Fork a child process. # Return 0 to child process and PID of child to parent process.""" - # return _posix.fork() + # return _posix_impl.fork() def kill(pid, sig): """kill(pid, sig) Kill a process with a signal.""" - return _posix.kill(pid, sig) + return _posix_impl.kill(pid, sig) def wait(): """wait() -> (pid, status) @@ -1063,7 +625,7 @@ Wait for completion of a child process.""" status = jarray.zeros(1, 'i') - res_pid = _posix.wait(status) + res_pid = _posix_impl.wait(status) if res_pid == -1: raise OSError(status[0], strerror(status[0])) return res_pid, status[0] @@ -1073,7 +635,7 @@ Wait for completion of a given child process.""" status = jarray.zeros(1, 'i') - res_pid = _posix.waitpid(pid, status, options) + res_pid = _posix_impl.waitpid(pid, status, options) if res_pid == -1: raise OSError(status[0], strerror(status[0])) return res_pid, status[0] @@ -1117,7 +679,7 @@ """getpid() -> pid Return the current process id.""" - return _posix.getpid() + return _posix_impl.getpid() def isatty(fileno): """isatty(fd) -> bool @@ -1137,10 +699,10 @@ raise NotImplemented('Integer file descriptor compatibility only ' 'available for stdin, stdout and stderr (0-2)') - return _posix.isatty(fd) + return _posix_impl.isatty(fd) if isinstance(fileno, FileDescriptor): - return _posix.isatty(fileno) + return _posix_impl.isatty(fileno) if not isinstance(fileno, IOBase): raise TypeError('a file descriptor is required') @@ -1151,16 +713,23 @@ """umask(new_mask) -> old_mask Set the current numeric umask and return the previous umask.""" - return _posix.umask(int(new_mask)) + return _posix_impl.umask(int(new_mask)) - -from java.security import SecureRandom -urandom_source = None - def urandom(n): global urandom_source if urandom_source is None: + from java.security import SecureRandom urandom_source = SecureRandom() buffer = jarray.zeros(n, 'b') urandom_source.nextBytes(buffer) return buffer.tostring() + +def _from_jnastat(s): + results = [] + for meth in (s.mode, s.ino, s.dev, s.nlink, s.uid, s.gid, s.st_size, + s.atime, s.mtime, s.ctime): + try: + results.append(meth()) + except NotImplementedError: + results.append(0) + return stat_result(results) Modified: trunk/jython/Lib/pwd.py =================================================================== --- trunk/jython/Lib/pwd.py 2009-10-19 21:56:07 UTC (rev 6873) +++ trunk/jython/Lib/pwd.py 2009-10-19 22:02:41 UTC (rev 6874) @@ -10,7 +10,7 @@ __all__ = ['getpwuid', 'getpwnam', 'getpwall'] -from os import _name, _posix +from os import _name, _posix_impl if _name == 'nt': raise ImportError, 'pwd module not supported on Windows' @@ -44,7 +44,7 @@ Return the password database entry for the given numeric user ID. See pwd.__doc__ for more on password database entries. """ - entry = _posix.getpwuid(uid) + entry = _posix_impl.getpwuid(uid) if not entry: raise KeyError(uid) return struct_passwd(entry) @@ -57,7 +57,7 @@ Return the password database entry for the given user name. See pwd.__doc__ for more on password database entries. """ - entry = _posix.getpwnam(name) + entry = _posix_impl.getpwnam(name) if not entry: raise KeyError(name) return struct_passwd(entry) @@ -72,7 +72,7 @@ """ entries = [] while True: - entry = _posix.getpwent() + entry = _posix_impl.getpwent() if not entry: break entries.append(struct_passwd(entry)) Modified: trunk/jython/Lib/select.py =================================================================== --- trunk/jython/Lib/select.py 2009-10-19 21:56:07 UTC (rev 6873) +++ trunk/jython/Lib/select.py 2009-10-19 22:02:41 UTC (rev 6874) @@ -180,7 +180,7 @@ class poll_object_cache: def __init__(self): - self.is_windows = os.get_os_type() == 'nt' + self.is_windows = os._name == 'nt' if self.is_windows: self.poll_object_queue = Queue.Queue() import atexit Modified: trunk/jython/Lib/subprocess.py =================================================================== --- trunk/jython/Lib/subprocess.py 2009-10-19 21:56:07 UTC (rev 6873) +++ trunk/jython/Lib/subprocess.py 2009-10-19 22:02:41 UTC (rev 6874) @@ -620,11 +620,7 @@ _cmdline2listimpl = lambda args: [args] _escape_args = lambda args: args - os_info = os._os_map.get(os._name) - if os_info is None: - os_info = os._os_map.get('posix') - - for shell_command in os_info[1]: + for shell_command in os._get_shell_commands(): executable = shell_command[0] if not os.path.isabs(executable): import distutils.spawn Modified: trunk/jython/Lib/test/test_import_jy.py =================================================================== --- trunk/jython/Lib/test/test_import_jy.py 2009-10-19 21:56:07 UTC (rev 6873) +++ trunk/jython/Lib/test/test_import_jy.py 2009-10-19 22:02:41 UTC (rev 6874) @@ -100,8 +100,8 @@ def test_override(self): modname = os.path.__name__ tests = [ - ("import os.path" , "('os.path', None, -1, 'os')" ), - ("import os.path as path2", "('os.path', None, -1, 'os')" ), + ("import os.path" , "('os.path', None, -1, '_posix')" ), + ("import os.path as path2", "('os.path', None, -1, '_posix')" ), ("from os.path import *" , "('os.path', ('*',), -1, '%s')" % modname), ("from os.path import join", Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2009-10-19 21:56:07 UTC (rev 6873) +++ trunk/jython/src/org/python/core/Py.java 2009-10-19 22:02:41 UTC (rev 6874) @@ -21,6 +21,7 @@ import java.util.Set; import org.python.antlr.base.mod; +import com.kenai.constantine.Constant; import com.kenai.constantine.platform.Errno; import java.util.ArrayList; import java.util.List; @@ -102,6 +103,12 @@ return new PyException(Py.OSError, message); } + public static PyException OSError(Constant errno, String filename) { + PyObject args = new PyTuple(Py.newInteger(errno.value()), Py.newString(errno.toString()), + Py.newString(filename)); + return new PyException(Py.OSError, args); + } + public static PyObject NotImplementedError; public static PyException NotImplementedError(String message) { return new PyException(Py.NotImplementedError, message); @@ -163,15 +170,14 @@ return new PyException(Py.IOError, message); } - public static PyException IOError(Errno errno) { - PyObject args = new PyTuple(Py.newInteger(errno.value()), - Py.newString(errno.description())); + public static PyException IOError(Constant errno) { + PyObject args = new PyTuple(Py.newInteger(errno.value()), Py.newString(errno.toString())); return new PyException(Py.IOError, args); } - public static PyException IOError(Errno errno, String filename) { - PyObject args = new PyTuple(Py.newInteger(errno.value()), - Py.newString(errno.description()), Py.newString(filename)); + public static PyException IOError(Constant errno, String filename) { + PyObject args = new PyTuple(Py.newInteger(errno.value()), Py.newString(errno.toString()), + Py.newString(filename)); return new PyException(Py.IOError, args); } Modified: trunk/jython/src/org/python/core/io/FileIO.java =================================================================== --- trunk/jython/src/org/python/core/io/FileIO.java 2009-10-19 21:56:07 UTC (rev 6873) +++ trunk/jython/src/org/python/core/io/FileIO.java 2009-10-19 22:02:41 UTC (rev 6874) @@ -16,8 +16,8 @@ import com.kenai.constantine.platform.Errno; import org.jruby.ext.posix.util.Platform; import org.python.core.Py; -import org.python.core.util.FileUtil; import org.python.core.util.RelativeFile; +import org.python.modules.posix.PosixModule; /** * Raw I/O implementation for OS files. @@ -222,7 +222,8 @@ return false; } try { - return FileUtil.isatty(file != null ? file.getFD() : fileOutputStream.getFD()); + return PosixModule.getPOSIX().isatty(file != null + ? file.getFD() : fileOutputStream.getFD()); } catch (IOException e) { return false; } Modified: trunk/jython/src/org/python/core/io/StreamIO.java =================================================================== --- trunk/jython/src/org/python/core/io/StreamIO.java 2009-10-19 21:56:07 UTC (rev 6873) +++ trunk/jython/src/org/python/core/io/StreamIO.java 2009-10-19 22:02:41 UTC (rev 6874) @@ -17,7 +17,7 @@ import java.nio.channels.WritableByteChannel; import org.python.core.Py; -import org.python.core.util.FileUtil; +import org.python.modules.posix.PosixModule; /** * Raw I/O implementation for simple streams. @@ -231,7 +231,7 @@ return false; } - return FileUtil.isatty(fd); + return PosixModule.getPOSIX().isatty(fd); } @Override Modified: trunk/jython/src/org/python/core/util/FileUtil.java =================================================================== --- trunk/jython/src/org/python/core/util/FileUtil.java 2009-10-19 21:56:07 UTC (rev 6873) +++ trunk/jython/src/org/python/core/util/FileUtil.java 2009-10-19 22:02:41 UTC (rev 6874) @@ -64,14 +64,4 @@ } return out.toByteArray(); } - - public static boolean isatty(FileDescriptor fd) { - try { - return imp.load("os").__getattr__("isatty").__call__(Py.java2py(fd)).__nonzero__(); - } catch (PyException e) { - // Weak isatty check copied from jna-posix JavaPOSIX class - return fd == FileDescriptor.in || fd == FileDescriptor.out || fd == FileDescriptor.err; - } - } - } Modified: trunk/jython/src/org/python/modules/Setup.java =================================================================== --- trunk/jython/src/org/python/modules/Setup.java 2009-10-19 21:56:07 UTC (rev 6873) +++ trunk/jython/src/org/python/modules/Setup.java 2009-10-19 22:02:41 UTC (rev 6874) @@ -1,6 +1,8 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.modules; +import org.python.modules.posix.PosixModule; + // This is sort of analogous to CPython's Modules/Setup file. Use this to // specify additional builtin modules. @@ -56,6 +58,7 @@ "_systemrestart", "_ast:org.python.antlr.ast.AstModule", "_marshal", - "_threading:org.python.modules._threading._threading" + "_threading:org.python.modules._threading._threading", + "_" + PosixModule.getOSName() + ":org.python.modules.posix.PosixModule" }; } Added: trunk/jython/src/org/python/modules/posix/OS.java =================================================================== --- trunk/jython/src/org/python/modules/posix/OS.java (rev 0) +++ trunk/jython/src/org/python/modules/posix/OS.java 2009-10-19 22:02:41 UTC (rev 6874) @@ -0,0 +1,90 @@ +/* Copyright (c) Jython Developers */ +package org.python.modules.posix; + +import java.lang.reflect.Method; + +import org.python.core.PyObject; +import org.python.core.PySystemState; + +/** + * A Marker tagging what OS we're running on, with some accompanying information about + * that platform. + */ +enum OS { + NT("Windows", new String[] {"cmd.exe", "/c"}, new String[] {"command.com", "/c"}), + POSIX(new String[] {"/bin/sh", "-c"}); + + /** An array of potential shell commands this platform may use. */ + private final String[][] shellCommands; + + /** + * Name to match against os.name System property for identification + * (os.name.startswith(pattern)). Defaults to name(). + */ + private final String pattern; + + OS(String pattern, String[]... shellCommands) { + this.shellCommands = shellCommands; + this.pattern = pattern != null ? pattern : name(); + } + + OS(String[]... shellCommands) { + this(null, shellCommands); + } + + String getModuleName() { + return name().toLowerCase(); + } + + String[][] getShellCommands() { + return shellCommands; + } + + /** + * Hide module level functions defined in the PosixModule dict not applicable to this + * OS, identified by the PosixModule.Hide annotation. + * + * @param dict The PosixModule module dict + */ + void hideFunctions(PyObject dict) { + for (Method method: PosixModule.class.getDeclaredMethods()) { + if (isHidden(method)) { + dict.__setitem__(method.getName(), null); + } + } + } + + /** + * Determine if method should be hidden for this OS. + * + * @param method a PosixModule Method + * @return true if should be hidden + */ + private boolean isHidden(Method method) { + if (method.isAnnotationPresent(PosixModule.Hide.class)) { + for (OS os : method.getAnnotation(PosixModule.Hide.class).value()) { + if (os == this) { + return true; + } + } + } + return false; + } + + /** + * Return the OS we're running on. + */ + static OS getOS() { + String osName = PySystemState.registry.getProperty("python.os"); + if (osName == null) { + osName = System.getProperty("os.name"); + } + + for (OS os : OS.values()) { + if (osName.startsWith(os.pattern)) { + return os; + } + } + return OS.POSIX; + } +} Added: trunk/jython/src/org/python/modules/posix/PosixModule.java =================================================================== --- trunk/jython/src/org/python/modules/posix/PosixModule.java (rev 0) +++ trunk/jython/src/org/python/modules/posix/PosixModule.java 2009-10-19 22:02:41 UTC (rev 6874) @@ -0,0 +1,115 @@ +/* Copyright (c) Jython Developers */ +package org.python.modules.posix; + +import com.kenai.constantine.Constant; +import com.kenai.constantine.ConstantSet; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.jruby.ext.posix.JavaPOSIX; +import org.jruby.ext.posix.POSIX; +import org.jruby.ext.posix.POSIXFactory; + +import org.python.core.ClassDictInit; +import org.python.core.Py; +import org.python.core.PyList; +import org.python.core.PyObject; +import org.python.core.PyString; +import org.python.core.PyTuple; + +/** + * The underlying _posix or _nt module, named depending on the platform. + * + * This currently contains only some of the basics of the posix/nt modules (which are + * implemented in Python). In particular things like the PythonPOSIXHandler that are + * slower to instantiate and thus would affect startup time. + * + * Eventually more if not all of the pure Python module should end up here. + */ +public class PosixModule implements ClassDictInit { + + public static final PyString __doc__ = new PyString( + "This module provides access to operating system functionality that is\n" + + "standardized by the C Standard and the POSIX standard (a thinly\n" + + "disguised Unix interface). Refer to the library manual and\n" + + "corresponding Unix manual entries for more information on calls."); + + /** Current OS information. */ + private static OS os = OS.getOS(); + + /** Platform specific POSIX services. */ + private static POSIX posix = POSIXFactory.getPOSIX(new PythonPOSIXHandler(), true); + + private static final String[] openFlags = + {"O_RDONLY", "O_WRONLY", "O_RDWR", "O_APPEND", "O_SYNC", "O_CREAT", "O_TRUNC", "O_EXCL"}; + + public static void classDictInit(PyObject dict) { + dict.__setitem__("__name__", new PyString("_" + os.getModuleName())); + dict.__setitem__("__doc__", __doc__); + + // os.open flags, only expose what we support + ConstantSet openFlagConstants = ConstantSet.getConstantSet("OpenFlags"); + for (String openFlag : openFlags) { + dict.__setitem__(openFlag, Py.newInteger(openFlagConstants.getValue(openFlag))); + } + // os.access constants + dict.__setitem__("F_OK", Py.Zero); + dict.__setitem__("X_OK", Py.newInteger(1 << 0)); + dict.__setitem__("W_OK", Py.newInteger(1 << 1)); + ... [truncated message content] |
From: <pj...@us...> - 2009-10-19 21:56:29
|
Revision: 6873 http://jython.svn.sourceforge.net/jython/?rev=6873&view=rev Author: pjenvey Date: 2009-10-19 21:56:07 +0000 (Mon, 19 Oct 2009) Log Message: ----------- move os.py -> posix.py, in prep. for separating the posix bits from it os.py from: http://svn.python.org/projects/python/branches/release26-maint/Lib/os.py@75144 Added Paths: ----------- trunk/jython/Lib/os.py trunk/jython/Lib/posix.py Removed Paths: ------------- trunk/jython/Lib/os.py trunk/jython/Lib/posix.py Deleted: trunk/jython/Lib/os.py =================================================================== --- trunk/jython/Lib/os.py 2009-10-19 21:26:09 UTC (rev 6872) +++ trunk/jython/Lib/os.py 2009-10-19 21:56:07 UTC (rev 6873) @@ -1,1166 +0,0 @@ -r"""OS routines for Java, with some attempts to support NT, and Posix -functionality. - -This exports: - - all functions from posix, nt, dos, os2, mac, or ce, e.g. unlink, stat, etc. - - os.path is one of the modules posixpath, ntpath, macpath, or dospath - - os.name is 'posix', 'nt', 'dos', 'os2', 'mac', 'ce' or 'riscos' - - os.curdir is a string representing the current directory ('.' or ':') - - os.pardir is a string representing the parent directory ('..' or '::') - - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\') - - os.altsep is the alternate pathname separator (None or '/') - - os.pathsep is the component separator used in $PATH etc - - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n') - - os.defpath is the default search path for executables - -Programs that import and use 'os' stand a better chance of being -portable between different platforms. Of course, they must then -only use functions that are defined by all platforms (e.g., unlink -and opendir), and leave all pathname manipulation to os.path -(e.g., split and join). -""" - -# CPython os.py __all__ -__all__ = ["altsep", "curdir", "pardir", "sep", "pathsep", "linesep", - "defpath", "name", "path", - "SEEK_SET", "SEEK_CUR", "SEEK_END"] - -# Would come from the posix/nt/etc. modules on CPython -__all__.extend(['EX_OK', 'F_OK', 'O_APPEND', 'O_CREAT', 'O_EXCL', 'O_RDONLY', - 'O_RDWR', 'O_SYNC', 'O_TRUNC', 'O_WRONLY', 'R_OK', 'SEEK_CUR', - 'SEEK_END', 'SEEK_SET', 'W_OK', 'X_OK', '_exit', 'access', - 'altsep', 'chdir', 'chmod', 'close', 'curdir', 'defpath', - 'environ', 'error', 'fdopen', 'fsync', 'getcwd', 'getcwdu', - 'getenv', 'getpid', 'isatty', 'linesep', 'listdir', 'lseek', - 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', - 'pathsep', 'popen', 'popen2', 'popen3', 'popen4', 'putenv', - 'read', 'remove', 'removedirs', 'rename', 'renames', 'rmdir', - 'sep', 'stat', 'stat_result', 'strerror', 'system', 'unlink', - 'unsetenv', 'utime', 'walk', 'write']) - -import errno -import jarray -import java.lang.System -import time -import stat as _stat -import sys -from java.io import File -from org.python.core.io import FileDescriptors, FileIO, IOBase -from org.python.core.Py import newString as asPyString - -try: - from org.python.constantine.platform import Errno -except ImportError: - from com.kenai.constantine.platform import Errno - -# Mapping of: os._name: [name list, shell command list] -_os_map = dict(nt=[ - ['Windows'], - [['cmd.exe', '/c'], ['command.com', '/c']] - ], - posix=[ - [], # posix is a fallback, instead of matching names - [['/bin/sh', '-c']] - ] - ) - -def get_os_type(): - """Return the name of the type of the underlying OS. - - Returns a value suitable for the os.name variable (though not - necessarily intended to be for os.name Jython). This value may be - overwritten in the Jython registry. - """ - os_name = sys.registry.getProperty('python.os') - if os_name: - return asPyString(os_name) - - os_name = asPyString(java.lang.System.getProperty('os.name')) - os_type = None - for type, (patterns, shell_commands) in _os_map.iteritems(): - for pattern in patterns: - if os_name.startswith(pattern): - # determine the shell_command later, when it's needed: - # it requires os.path (which isn't setup yet) - return type - return 'posix' - -name = 'java' -# WARNING: _name is private: for Jython internal usage only! user code -# should *NOT* use it -_name = get_os_type() - -try: - from org.python.posix import JavaPOSIX, POSIXHandler, POSIXFactory -except ImportError: - from org.jruby.ext.posix import JavaPOSIX, POSIXHandler, POSIXFactory - -class PythonPOSIXHandler(POSIXHandler): - def error(self, error, msg): - err = getattr(errno, error.name(), None) - if err is None: - raise OSError('%s: %s' % (error, asPyString(msg))) - raise OSError(err, strerror(err), asPyString(msg)) - def unimplementedError(self, method_name): - raise NotImplementedError(method_name) - def warn(self, warning_id, msg, rest): - pass # XXX implement - def isVerbose(self): - return False - def getCurrentWorkingDirectory(self): - return File(getcwdu()) - def getEnv(self): - return ['%s=%s' % (key, val) for key, val in environ.iteritems()] - def getInputStream(self): - return getattr(java.lang.System, 'in') # XXX handle resetting - def getOutputStream(self): - return java.lang.System.out # XXX handle resetting - def getPID(self): - return 0 - def getErrorStream(self): - return java.lang.System.err # XXX handle resetting - -_posix = POSIXFactory.getPOSIX(PythonPOSIXHandler(), True) -_native_posix = not isinstance(_posix, JavaPOSIX) - -if _name == 'nt': - import ntpath as path -else: - import posixpath as path - -sys.modules['os.path'] = _path = path -from os.path import curdir, pardir, sep, pathsep, defpath, extsep, altsep, devnull -linesep = java.lang.System.getProperty('line.separator') - -# open for reading only -O_RDONLY = 0x0 -# open for writing only -O_WRONLY = 0x1 -# open for reading and writing -O_RDWR = 0x2 - -# set append mode -O_APPEND = 0x8 -# synchronous writes -O_SYNC = 0x80 - -# create if nonexistant -O_CREAT = 0x200 -# truncate to zero length -O_TRUNC = 0x400 -# error if already exists -O_EXCL = 0x800 - -# seek variables -SEEK_SET = 0 -SEEK_CUR = 1 -SEEK_END = 2 - -# test for existence of file -F_OK = 0 -# test for execute or search permission -X_OK = 1<<0 -# test for write permission -W_OK = 1<<1 -# test for read permission -R_OK = 1<<2 - -# successful termination -EX_OK = 0 - -# Java class representing the size of a time_t. internal use, lazily set -_time_t = None - -class stat_result: - - _stat_members = ( - ('st_mode', _stat.ST_MODE), - ('st_ino', _stat.ST_INO), - ('st_dev', _stat.ST_DEV), - ('st_nlink', _stat.ST_NLINK), - ('st_uid', _stat.ST_UID), - ('st_gid', _stat.ST_GID), - ('st_size', _stat.ST_SIZE), - ('st_atime', _stat.ST_ATIME), - ('st_mtime', _stat.ST_MTIME), - ('st_ctime', _stat.ST_CTIME), - ) - - def __init__(self, results): - if len(results) != 10: - raise TypeError("stat_result() takes an a 10-sequence") - for (name, index) in stat_result._stat_members: - self.__dict__[name] = results[index] - - @classmethod - def from_jnastat(cls, s): - results = [] - for meth in (s.mode, s.ino, s.dev, s.nlink, s.uid, s.gid, s.st_size, - s.atime, s.mtime, s.ctime): - try: - results.append(meth()) - except NotImplementedError: - results.append(0) - return cls(results) - - def __getitem__(self, i): - if i < 0 or i > 9: - raise IndexError(i) - return getattr(self, stat_result._stat_members[i][0]) - - def __setitem__(self, x, value): - raise TypeError("object doesn't support item assignment") - - def __setattr__(self, name, value): - if name in [x[0] for x in stat_result._stat_members]: - raise TypeError(name) - raise AttributeError("readonly attribute") - - def __len__(self): - return 10 - - def __cmp__(self, other): - if not isinstance(other, stat_result): - return 1 - return cmp(self.__dict__, other.__dict__) - - def __repr__(self): - return repr(tuple(self.__dict__[member[0]] for member - in stat_result._stat_members)) - -error = OSError - -def _exit(n=0): - """_exit(status) - - Exit to the system with specified status, without normal exit - processing. - """ - java.lang.System.exit(n) - -def getcwd(): - """getcwd() -> path - - Return a string representing the current working directory. - """ - return asPyString(sys.getCurrentWorkingDir()) - -def getcwdu(): - """getcwd() -> path - - Return a unicode string representing the current working directory. - """ - return sys.getCurrentWorkingDir() - -def chdir(path): - """chdir(path) - - Change the current working directory to the specified path. - """ - realpath = _path.realpath(path) - if not _path.exists(realpath): - raise OSError(errno.ENOENT, strerror(errno.ENOENT), path) - if not _path.isdir(realpath): - raise OSError(errno.ENOTDIR, strerror(errno.ENOTDIR), path) - sys.setCurrentWorkingDir(realpath) - -def listdir(path): - """listdir(path) -> list_of_strings - - Return a list containing the names of the entries in the directory. - - path: path of directory to list - - The list is in arbitrary order. It does not include the special - entries '.' and '..' even if they are present in the directory. - """ - l = File(sys.getPath(path)).list() - if l is None: - raise OSError(0, 'No such directory', path) - return [asPyString(entry) for entry in l] - -def chmod(path, mode): - """chmod(path, mode) - - Change the access permissions of a file. - """ - # XXX no error handling for chmod in jna-posix - # catch not found errors explicitly here, for now - abs_path = sys.getPath(path) - if not File(abs_path).exists(): - raise OSError(errno.ENOENT, strerror(errno.ENOENT), path) - _posix.chmod(abs_path, mode) - -def mkdir(path, mode='ignored'): - """mkdir(path [, mode=0777]) - - Create a directory. - - The optional parameter is currently ignored. - """ - # XXX: use _posix.mkdir when we can get the real errno upon failure - fp = File(sys.getPath(path)) - if not fp.mkdir(): - if fp.isDirectory() or fp.isFile(): - err = errno.EEXIST - else: - err = 0 - msg = strerror(err) if err else "couldn't make directory" - raise OSError(err, msg, path) - -def makedirs(path, mode='ignored'): - """makedirs(path [, mode=0777]) - - Super-mkdir; create a leaf directory and all intermediate ones. - - Works like mkdir, except that any intermediate path segment (not - just the rightmost) will be created if it does not exist. - The optional parameter is currently ignored. - """ - sys_path = sys.getPath(path) - if File(sys_path).mkdirs(): - return - - # if making a /x/y/z/., java.io.File#mkdirs inexplicably fails. So we need - # to force it - - # need to use _path instead of path, because param is hiding - # os.path module in namespace! - head, tail = _path.split(sys_path) - if tail == curdir: - if File(_path.join(head)).mkdirs(): - return - - raise OSError(0, "couldn't make directories", path) - -def remove(path): - """remove(path) - - Remove a file (same as unlink(path)). - """ - if not File(sys.getPath(path)).delete(): - raise OSError(0, "couldn't delete file", path) - -unlink = remove - -def rename(path, newpath): - """rename(old, new) - - Rename a file or directory. - """ - if not File(sys.getPath(path)).renameTo(File(sys.getPath(newpath))): - raise OSError(0, "couldn't rename file", path) - -#XXX: copied from CPython 2.5.1 -def renames(old, new): - """renames(old, new) - - Super-rename; create directories as necessary and delete any left - empty. Works like rename, except creation of any intermediate - directories needed to make the new pathname good is attempted - first. After the rename, directories corresponding to rightmost - path segments of the old name will be pruned way until either the - whole path is consumed or a nonempty directory is found. - - Note: this function can fail with the new directory structure made - if you lack permissions needed to unlink the leaf directory or - file. - - """ - head, tail = path.split(new) - if head and tail and not path.exists(head): - makedirs(head) - rename(old, new) - head, tail = path.split(old) - if head and tail: - try: - removedirs(head) - except error: - pass - -def rmdir(path): - """rmdir(path) - - Remove a directory.""" - f = File(sys.getPath(path)) - if not f.exists(): - raise OSError(errno.ENOENT, strerror(errno.ENOENT), path) - elif not f.isDirectory(): - raise OSError(errno.ENOTDIR, strerror(errno.ENOTDIR), path) - elif not f.delete(): - raise OSError(0, "couldn't delete directory", path) - -#XXX: copied from CPython 2.5.1 -def removedirs(name): - """removedirs(path) - - Super-rmdir; remove a leaf directory and empty all intermediate - ones. Works like rmdir except that, if the leaf directory is - successfully removed, directories corresponding to rightmost path - segments will be pruned away until either the whole path is - consumed or an error occurs. Errors during this latter phase are - ignored -- they generally mean that a directory was not empty. - - """ - rmdir(name) - head, tail = path.split(name) - if not tail: - head, tail = path.split(head) - while head and tail: - try: - rmdir(head) - except error: - break - head, tail = path.split(head) - -__all__.extend(['makedirs', 'renames', 'removedirs']) - -def strerror(code): - """strerror(code) -> string - - Translate an error code to a message string. - """ - if not isinstance(code, (int, long)): - raise TypeError('an integer is required') - constant = Errno.valueOf(code) - if constant is Errno.__UNKNOWN_CONSTANT__: - return 'Unknown error: %d' % code - if constant.name() == constant.description(): - # XXX: have constantine handle this fallback - # Fake constant or just lacks a description, fallback to Linux's - try: - from org.python.constantine.platform.linux import Errno as LinuxErrno - except ImportError: - from com.kenai.constantine.platform.linux import Errno as LinuxErrno - constant = getattr(LinuxErrno, constant.name(), None) - if not constant: - return 'Unknown error: %d' % code - return asPyString(constant.toString()) - -def access(path, mode): - """access(path, mode) -> True if granted, False otherwise - - Use the real uid/gid to test for access to a path. Note that most - operations will use the effective uid/gid, therefore this routine can - be used in a suid/sgid environment to test if the invoking user has the - specified access to the path. The mode argument can be F_OK to test - existence, or the inclusive-OR of R_OK, W_OK, and X_OK. - """ - if not isinstance(mode, (int, long)): - raise TypeError('an integer is required') - - f = File(sys.getPath(path)) - result = True - if not f.exists(): - result = False - if mode & R_OK and not f.canRead(): - result = False - if mode & W_OK and not f.canWrite(): - result = False - if mode & X_OK: - # NOTE: always False without jna-posix stat - try: - result = (stat(path).st_mode & _stat.S_IEXEC) != 0 - except OSError: - result = False - return result - -def stat(path): - """stat(path) -> stat result - - Perform a stat system call on the given path. - - The Java stat implementation only returns a small subset of - the standard fields: size, modification time and change time. - """ - abs_path = sys.getPath(path) - try: - return stat_result.from_jnastat(_posix.stat(abs_path)) - except NotImplementedError: - pass - f = File(abs_path) - if not f.exists(): - raise OSError(errno.ENOENT, strerror(errno.ENOENT), path) - size = f.length() - mtime = f.lastModified() / 1000.0 - mode = 0 - if f.isDirectory(): - mode = _stat.S_IFDIR - elif f.isFile(): - mode = _stat.S_IFREG - if f.canRead(): - mode = mode | _stat.S_IREAD - if f.canWrite(): - mode = mode | _stat.S_IWRITE - return stat_result((mode, 0, 0, 0, 0, 0, size, mtime, mtime, 0)) - -def lstat(path): - """lstat(path) -> stat result - - Like stat(path), but do not follow symbolic links. - """ - abs_path = sys.getPath(path) - try: - return stat_result.from_jnastat(_posix.lstat(abs_path)) - except NotImplementedError: - pass - f = File(sys.getPath(path)) - # XXX: jna-posix implements similar link detection in - # JavaFileStat.calculateSymlink, fallback to that instead when not - # native - abs_parent = f.getAbsoluteFile().getParentFile() - if not abs_parent: - # root isn't a link - return stat(path) - can_parent = abs_parent.getCanonicalFile() - - if can_parent.getAbsolutePath() == abs_parent.getAbsolutePath(): - # The parent directory's absolute path is canonical.. - if f.getAbsolutePath() != f.getCanonicalPath(): - # but the file's absolute and canonical paths differ (a - # link) - return stat_result((_stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0)) - - # The parent directory's path is not canonical (one of the parent - # directories is a symlink). Build a new path with the parent's - # canonical path and compare the files - f = File(_path.join(can_parent.getAbsolutePath(), f.getName())) - if f.getAbsolutePath() != f.getCanonicalPath(): - return stat_result((_stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0)) - - # Not a link, only now can we determine if it exists (because - # File.exists() returns False for dead links) - if not f.exists(): - raise OSError(errno.ENOENT, strerror(errno.ENOENT), path) - return stat(path) - -def utime(path, times): - """utime(path, (atime, mtime)) - utime(path, None) - - Set the access and modification time of the file to the given values. - If the second form is used, set the access and modification times to the - current time. - - Due to Java limitations, on some platforms only the modification time - may be changed. - """ - if path is None: - raise TypeError('path must be specified, not None') - - if times is None: - atimeval = mtimeval = None - elif isinstance(times, tuple) and len(times) == 2: - atimeval = _to_timeval(times[0]) - mtimeval = _to_timeval(times[1]) - else: - raise TypeError('utime() arg 2 must be a tuple (atime, mtime)') - - _posix.utimes(path, atimeval, mtimeval) - -def _to_timeval(seconds): - """Convert seconds (with a fraction) from epoch to a 2 item tuple of - seconds, microseconds from epoch as longs - """ - global _time_t - if _time_t is None: - from java.lang import Integer, Long - try: - from org.python.posix.util import Platform - except ImportError: - from org.jruby.ext.posix.util import Platform - _time_t = Integer if Platform.IS_32_BIT else Long - - try: - floor = long(seconds) - except TypeError: - raise TypeError('an integer is required') - if not _time_t.MIN_VALUE <= floor <= _time_t.MAX_VALUE: - raise OverflowError('long int too large to convert to int') - - # usec can't exceed 1000000 - usec = long((seconds - floor) * 1e6) - if usec < 0: - # If rounding gave us a negative number, truncate - usec = 0 - return floor, usec - -def close(fd): - """close(fd) - - Close a file descriptor (for low level IO). - """ - rawio = FileDescriptors.get(fd) - _handle_oserror(rawio.close) - -def fdopen(fd, mode='r', bufsize=-1): - """fdopen(fd [, mode='r' [, bufsize]]) -> file_object - - Return an open file object connected to a file descriptor. - """ - rawio = FileDescriptors.get(fd) - if (len(mode) and mode[0] or '') not in 'rwa': - raise ValueError("invalid file mode '%s'" % mode) - if rawio.closed(): - raise OSError(errno.EBADF, strerror(errno.EBADF)) - - try: - fp = FileDescriptors.wrap(rawio, mode, bufsize) - except IOError: - raise OSError(errno.EINVAL, strerror(errno.EINVAL)) - return fp - -def ftruncate(fd, length): - """ftruncate(fd, length) - - Truncate a file to a specified length. - """ - rawio = FileDescriptors.get(fd) - try: - rawio.truncate(length) - except Exception, e: - raise IOError(errno.EBADF, strerror(errno.EBADF)) - -def lseek(fd, pos, how): - """lseek(fd, pos, how) -> newpos - - Set the current position of a file descriptor. - """ - rawio = FileDescriptors.get(fd) - return _handle_oserror(rawio.seek, pos, how) - -def open(filename, flag, mode=0777): - """open(filename, flag [, mode=0777]) -> fd - - Open a file (for low level IO). - """ - reading = flag & O_RDONLY - writing = flag & O_WRONLY - updating = flag & O_RDWR - creating = flag & O_CREAT - - truncating = flag & O_TRUNC - exclusive = flag & O_EXCL - sync = flag & O_SYNC - appending = flag & O_APPEND - - if updating and writing: - raise OSError(errno.EINVAL, strerror(errno.EINVAL), filename) - - if not creating and not path.exists(filename): - raise OSError(errno.ENOENT, strerror(errno.ENOENT), filename) - - if not writing: - if updating: - writing = True - else: - reading = True - - if truncating and not writing: - # Explicitly truncate, writing will truncate anyway - FileIO(filename, 'w').close() - - if exclusive and creating: - try: - if not File(sys.getPath(filename)).createNewFile(): - raise OSError(errno.EEXIST, strerror(errno.EEXIST), - filename) - except java.io.IOException, ioe: - raise OSError(ioe) - - mode = '%s%s%s%s' % (reading and 'r' or '', - (not appending and writing) and 'w' or '', - (appending and (writing or updating)) and 'a' or '', - updating and '+' or '') - - if sync and (writing or updating): - from java.io import FileNotFoundException, RandomAccessFile - try: - fchannel = RandomAccessFile(sys.getPath(filename), 'rws').getChannel() - except FileNotFoundException, fnfe: - if path.isdir(filename): - raise OSError(errno.EISDIR, strerror(errno.EISDIR)) - raise OSError(errno.ENOENT, strerror(errno.ENOENT), filename) - return FileIO(fchannel, mode) - - return FileIO(filename, mode) - -def read(fd, buffersize): - """read(fd, buffersize) -> string - - Read a file descriptor. - """ - from org.python.core.util import StringUtil - rawio = FileDescriptors.get(fd) - buf = _handle_oserror(rawio.read, buffersize) - return asPyString(StringUtil.fromBytes(buf)) - -def write(fd, string): - """write(fd, string) -> byteswritten - - Write a string to a file descriptor. - """ - from java.nio import ByteBuffer - from org.python.core.util import StringUtil - rawio = FileDescriptors.get(fd) - return _handle_oserror(rawio.write, - ByteBuffer.wrap(StringUtil.toBytes(string))) - -def _handle_oserror(func, *args, **kwargs): - """Translate exceptions into OSErrors""" - try: - return func(*args, **kwargs) - except: - raise OSError(errno.EBADF, strerror(errno.EBADF)) - -def system(command): - """system(command) -> exit_status - - Execute the command (a string) in a subshell. - """ - import subprocess - return subprocess.call(command, shell=True) - -def popen(command, mode='r', bufsize=-1): - """popen(command [, mode='r' [, bufsize]]) -> pipe - - Open a pipe to/from a command returning a file object. - """ - import subprocess - if mode == 'r': - proc = subprocess.Popen(command, bufsize=bufsize, shell=True, - stdout=subprocess.PIPE) - return _wrap_close(proc.stdout, proc) - elif mode == 'w': - proc = subprocess.Popen(command, bufsize=bufsize, shell=True, - stdin=subprocess.PIPE) - return _wrap_close(proc.stdin, proc) - else: - raise OSError(errno.EINVAL, strerror(errno.EINVAL)) - -# Helper for popen() -- a proxy for a file whose close waits for the process -class _wrap_close(object): - def __init__(self, stream, proc): - self._stream = stream - self._proc = proc - def close(self): - self._stream.close() - returncode = self._proc.wait() - if returncode == 0: - return None - if _name == 'nt': - return returncode - else: - return returncode - def __getattr__(self, name): - return getattr(self._stream, name) - def __iter__(self): - return iter(self._stream) - -# os module versions of the popen# methods have different return value -# order than popen2 functions - -def popen2(cmd, mode="t", bufsize=-1): - """Execute the shell command cmd in a sub-process. - - On UNIX, 'cmd' may be a sequence, in which case arguments will be - passed directly to the program without shell intervention (as with - os.spawnv()). If 'cmd' is a string it will be passed to the shell - (as with os.system()). If 'bufsize' is specified, it sets the - buffer size for the I/O pipes. The file objects (child_stdin, - child_stdout) are returned. - """ - import popen2 - stdout, stdin = popen2.popen2(cmd, bufsize) - return stdin, stdout - -def popen3(cmd, mode="t", bufsize=-1): - """Execute the shell command 'cmd' in a sub-process. - - On UNIX, 'cmd' may be a sequence, in which case arguments will be - passed directly to the program without shell intervention - (as with os.spawnv()). If 'cmd' is a string it will be passed - to the shell (as with os.system()). If 'bufsize' is specified, - it sets the buffer size for the I/O pipes. The file objects - (child_stdin, child_stdout, child_stderr) are returned. - """ - import popen2 - stdout, stdin, stderr = popen2.popen3(cmd, bufsize) - return stdin, stdout, stderr - -def popen4(cmd, mode="t", bufsize=-1): - """Execute the shell command 'cmd' in a sub-process. - - On UNIX, 'cmd' may be a sequence, in which case arguments will be - passed directly to the program without shell intervention - (as with os.spawnv()). If 'cmd' is a string it will be passed - to the shell (as with os.system()). If 'bufsize' is specified, - it sets the buffer size for the I/O pipes. The file objects - (child_stdin, child_stdout_stderr) are returned. - """ - import popen2 - stdout, stdin = popen2.popen4(cmd, bufsize) - return stdin, stdout - -def getlogin(): - """getlogin() -> string - - Return the actual login name. - """ - return java.lang.System.getProperty("user.name") - -#XXX: copied from CPython's release23-maint branch revision 56502 -def walk(top, topdown=True, onerror=None): - """Directory tree generator. - - For each directory in the directory tree rooted at top (including top - itself, but excluding '.' and '..'), yields a 3-tuple - - dirpath, dirnames, filenames - - dirpath is a string, the path to the directory. dirnames is a list of - the names of the subdirectories in dirpath (excluding '.' and '..'). - filenames is a list of the names of the non-directory files in dirpath. - Note that the names in the lists are just names, with no path components. - To get a full path (which begins with top) to a file or directory in - dirpath, do os.path.join(dirpath, name). - - If optional arg 'topdown' is true or not specified, the triple for a - directory is generated before the triples for any of its subdirectories - (directories are generated top down). If topdown is false, the triple - for a directory is generated after the triples for all of its - subdirectories (directories are generated bottom up). - - When topdown is true, the caller can modify the dirnames list in-place - (e.g., via del or slice assignment), and walk will only recurse into the - subdirectories whose names remain in dirnames; this can be used to prune - the search, or to impose a specific order of visiting. Modifying - dirnames when topdown is false is ineffective, since the directories in - dirnames have already been generated by the time dirnames itself is - generated. - - By default errors from the os.listdir() call are ignored. If - optional arg 'onerror' is specified, it should be a function; it - will be called with one argument, an os.error instance. It can - report the error to continue with the walk, or raise the exception - to abort the walk. Note that the filename is available as the - filename attribute of the exception object. - - Caution: if you pass a relative pathname for top, don't change the - current working directory between resumptions of walk. walk never - changes the current directory, and assumes that the client doesn't - either. - - Example: - - from os.path import join, getsize - for root, dirs, files in walk('python/Lib/email'): - print root, "consumes", - print sum([getsize(join(root, name)) for name in files]), - print "bytes in", len(files), "non-directory files" - if 'CVS' in dirs: - dirs.remove('CVS') # don't visit CVS directories - """ - - from os.path import join, isdir, islink - - # We may not have read permission for top, in which case we can't - # get a list of the files the directory contains. os.path.walk - # always suppressed the exception then, rather than blow up for a - # minor reason when (say) a thousand readable directories are still - # left to visit. That logic is copied here. - try: - # Note that listdir and error are globals in this module due - # to earlier import-*. - names = listdir(top) - except error, err: - if onerror is not None: - onerror(err) - return - - dirs, nondirs = [], [] - for name in names: - if isdir(join(top, name)): - dirs.append(name) - else: - nondirs.append(name) - - if topdown: - yield top, dirs, nondirs - for name in dirs: - path = join(top, name) - if not islink(path): - for x in walk(path, topdown, onerror): - yield x - if not topdown: - yield top, dirs, nondirs - -__all__.append("walk") - -environ = sys.getEnviron() - -if _name in ('os2', 'nt'): # Where Env Var Names Must Be UPPERCASE - import UserDict - - # But we store them as upper case - class _Environ(UserDict.IterableUserDict): - def __init__(self, environ): - UserDict.UserDict.__init__(self) - data = self.data - for k, v in environ.items(): - data[k.upper()] = v - def __setitem__(self, key, item): - self.data[key.upper()] = item - def __getitem__(self, key): - return self.data[key.upper()] - def __delitem__(self, key): - del self.data[key.upper()] - def has_key(self, key): - return key.upper() in self.data - def __contains__(self, key): - return key.upper() in self.data - def get(self, key, failobj=None): - return self.data.get(key.upper(), failobj) - def update(self, dict=None, **kwargs): - if dict: - try: - keys = dict.keys() - except AttributeError: - # List of (key, value) - for k, v in dict: - self[k] = v - else: - # got keys - # cannot use items(), since mappings - # may not have them. - for k in keys: - self[k] = dict[k] - if kwargs: - self.update(kwargs) - def copy(self): - return dict(self) - - environ = _Environ(environ) - -def putenv(key, value): - """putenv(key, value) - - Change or add an environment variable. - """ - environ[key] = value - -def unsetenv(key): - """unsetenv(key) - - Delete an environment variable. - """ - if key in environ: - del environ[key] - -def getenv(key, default=None): - """Get an environment variable, return None if it doesn't exist. - The optional second argument can specify an alternate default.""" - return environ.get(key, default) - -if _name == 'posix': - def link(src, dst): - """link(src, dst) - - Create a hard link to a file. - """ - _posix.link(sys.getPath(src), sys.getPath(dst)) - - def symlink(src, dst): - """symlink(src, dst) - - Create a symbolic link pointing to src named dst. - """ - _posix.symlink(src, sys.getPath(dst)) - - def readlink(path): - """readlink(path) -> path - - Return a string representing the path to which the symbolic link - points. - """ - return _posix.readlink(sys.getPath(path)) - - def getegid(): - """getegid() -> egid - - Return the current process's effective group id.""" - return _posix.getegid() - - def geteuid(): - """geteuid() -> euid - - Return the current process's effective user id.""" - return _posix.geteuid() - - def getgid(): - """getgid() -> gid - - Return the current process's group id.""" - return _posix.getgid() - - def getlogin(): - """getlogin() -> string - - Return the actual login name.""" - return _posix.getlogin() - - def getpgrp(): - """getpgrp() -> pgrp - - Return the current process group id.""" - return _posix.getpgrp() - - def getppid(): - """getppid() -> ppid - - Return the parent's process id.""" - return _posix.getppid() - - def getuid(): - """getuid() -> uid - - Return the current process's user id.""" - return _posix.getuid() - - def setpgrp(): - """setpgrp() - - Make this process a session leader.""" - return _posix.setpgrp() - - def setsid(): - """setsid() - - Call the system call setsid().""" - return _posix.setsid() - - # This implementation of fork partially works on - # Jython. Diagnosing what works, what doesn't, and fixing it is - # left for another day. In any event, this would only be - # marginally useful. - - # def fork(): - # """fork() -> pid - # - # Fork a child process. - # Return 0 to child process and PID of child to parent process.""" - # return _posix.fork() - - def kill(pid, sig): - """kill(pid, sig) - - Kill a process with a signal.""" - return _posix.kill(pid, sig) - - def wait(): - """wait() -> (pid, status) - - Wait for completion of a child process.""" - - status = jarray.zeros(1, 'i') - res_pid = _posix.wait(status) - if res_pid == -1: - raise OSError(status[0], strerror(status[0])) - return res_pid, status[0] - - def waitpid(pid, options): - """waitpid(pid, options) -> (pid, status) - - Wait for completion of a given child process.""" - status = jarray.zeros(1, 'i') - res_pid = _posix.waitpid(pid, status, options) - if res_pid == -1: - raise OSError(status[0], strerror(status[0])) - return res_pid, status[0] - - def fdatasync(fd): - """fdatasync(fildes) - - force write of file with filedescriptor to disk. - does not force update of metadata. - """ - _fsync(fd, False) - - __all__.extend(['link', 'symlink', 'readlink', 'getegid', 'geteuid', - 'getgid', 'getlogin', 'getpgrp', 'getppid', 'getuid', - 'setpgrp', 'setsid', 'kill', 'wait', 'waitpid', - 'fdatasync']) - -def fsync(fd): - """fsync(fildes) - - force write of file with filedescriptor to disk. - """ - _fsync(fd, True) - -def _fsync(fd, metadata): - """Internal fsync impl""" - rawio = FileDescriptors.get(fd) - rawio.checkClosed() - - from java.nio.channels import FileChannel - channel = rawio.getChannel() - if not isinstance(channel, FileChannel): - raise OSError(errno.EINVAL, strerror(errno.EINVAL)) - - try: - channel.force(metadata) - except java.io.IOException, ioe: - raise OSError(ioe) - -def getpid(): - """getpid() -> pid - - Return the current process id.""" - return _posix.getpid() - -def isatty(fileno): - """isatty(fd) -> bool - - Return True if the file descriptor 'fd' is an open file descriptor - connected to the slave end of a terminal.""" - from java.io import FileDescriptor - - if isinstance(fileno, int): - if fileno == 0: - fd = getattr(FileDescriptor, 'in') - elif fileno == 1: - fd = FileDescriptor.out - elif fileno == 2: - fd = FileDescriptor.err - else: - raise NotImplemented('Integer file descriptor compatibility only ' - 'available for stdin, stdout and stderr (0-2)') - - return _posix.isatty(fd) - - if isinstance(fileno, FileDescriptor): - return _posix.isatty(fileno) - - if not isinstance(fileno, IOBase): - raise TypeError('a file descriptor is required') - - return fileno.isatty() - -def umask(new_mask): - """umask(new_mask) -> old_mask - - Set the current numeric umask and return the previous umask.""" - return _posix.umask(int(new_mask)) - - -from java.security import SecureRandom -urandom_source = None - -def urandom(n): - global urandom_source - if urandom_source is None: - urandom_source = SecureRandom() - buffer = jarray.zeros(n, 'b') - urandom_source.nextBytes(buffer) - return buffer.tostring() Added: trunk/jython/Lib/os.py =================================================================== --- trunk/jython/Lib/os.py (rev 0) +++ trunk/jython/Lib/os.py 2009-10-19 21:56:07 UTC (rev 6873) @@ -0,0 +1,763 @@ +r"""OS routines for Mac, NT, or Posix depending on what system we're on. + +This exports: + - all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc. + - os.path is one of the modules posixpath, or ntpath + - os.name is 'posix', 'nt', 'os2', 'ce' or 'riscos' + - os.curdir is a string representing the current directory ('.' or ':') + - os.pardir is a string representing the parent directory ('..' or '::') + - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\') + - os.extsep is the extension separator ('.' or '/') + - os.altsep is the alternate pathname separator (None or '/') + - os.pathsep is the component separator used in $PATH etc + - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n') + - os.defpath is the default search path for executables + - os.devnull is the file path of the null device ('/dev/null', etc.) + +Programs that import and use 'os' stand a better chance of being +portable between different platforms. Of course, they must then +only use functions that are defined by all platforms (e.g., unlink +and opendir), and leave all pathname manipulation to os.path +(e.g., split and join). +""" + +#' + +import sys, errno + +_names = sys.builtin_module_names + +# Note: more names are added to __all__ later. +__all__ = ["altsep", "curdir", "pardir", "sep", "extsep", "pathsep", "linesep", + "defpath", "name", "path", "devnull", + "SEEK_SET", "SEEK_CUR", "SEEK_END"] + +def _get_exports_list(module): + try: + return list(module.__all__) + except AttributeError: + return [n for n in dir(module) if n[0] != '_'] + +if 'posix' in _names: + name = 'posix' + linesep = '\n' + from posix import * + try: + from posix import _exit + except ImportError: + pass + import posixpath as path + + import posix + __all__.extend(_get_exports_list(posix)) + del posix + +elif 'nt' in _names: + name = 'nt' + linesep = '\r\n' + from nt import * + try: + from nt import _exit + except ImportError: + pass + import ntpath as path + + import nt + __all__.extend(_get_exports_list(nt)) + del nt + +elif 'os2' in _names: + name = 'os2' + linesep = '\r\n' + from os2 import * + try: + from os2 import _exit + except ImportError: + pass + if sys.version.find('EMX GCC') == -1: + import ntpath as path + else: + import os2emxpath as path + from _emx_link import link + + import os2 + __all__.extend(_get_exports_list(os2)) + del os2 + +elif 'ce' in _names: + name = 'ce' + linesep = '\r\n' + from ce import * + try: + from ce import _exit + except ImportError: + pass + # We can use the standard Windows path. + import ntpath as path + + import ce + __all__.extend(_get_exports_list(ce)) + del ce + +elif 'riscos' in _names: + name = 'riscos' + linesep = '\n' + from riscos import * + try: + from riscos import _exit + except ImportError: + pass + import riscospath as path + + import riscos + __all__.extend(_get_exports_list(riscos)) + del riscos + +else: + raise ImportError, 'no os specific module found' + +sys.modules['os.path'] = path +from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep, + devnull) + +del _names + +# Python uses fixed values for the SEEK_ constants; they are mapped +# to native constants if necessary in posixmodule.c +SEEK_SET = 0 +SEEK_CUR = 1 +SEEK_END = 2 + +#' + +# Super directory utilities. +# (Inspired by Eric Raymond; the doc strings are mostly his) + +def makedirs(name, mode=0777): + """makedirs(path [, mode=0777]) + + Super-mkdir; create a leaf directory and all intermediate ones. + Works like mkdir, except that any intermediate path segment (not + just the rightmost) will be created if it does not exist. This is + recursive. + + """ + head, tail = path.split(name) + if not tail: + head, tail = path.split(head) + if head and tail and not path.exists(head): + try: + makedirs(head, mode) + except OSError, e: + # be happy if someone already created the path + if e.errno != errno.EEXIST: + raise + if tail == curdir: # xxx/newdir/. exists if xxx/newdir exists + return + mkdir(name, mode) + +def removedirs(name): + """removedirs(path) + + Super-rmdir; remove a leaf directory and all empty intermediate + ones. Works like rmdir except that, if the leaf directory is + successfully removed, directories corresponding to rightmost path + segments will be pruned away until either the whole path is + consumed or an error occurs. Errors during this latter phase are + ignored -- they generally mean that a directory was not empty. + + """ + rmdir(name) + head, tail = path.split(name) + if not tail: + head, tail = path.split(head) + while head and tail: + try: + rmdir(head) + except error: + break + head, tail = path.split(head) + +def renames(old, new): + """renames(old, new) + + Super-rename; create directories as necessary and delete any left + empty. Works like rename, except creation of any intermediate + directories needed to make the new pathname good is attempted + first. After the rename, directories corresponding to rightmost + path segments of the old name will be pruned way until either the + whole path is consumed or a nonempty directory is found. + + Note: this function can fail with the new directory structure made + if you lack permissions needed to unlink the leaf directory or + file. + + """ + head, tail = path.split(new) + if head and tail and not path.exists(head): + makedirs(head) + rename(old, new) + head, tail = path.split(old) + if head and tail: + try: + removedirs(head) + except error: + pass + +__all__.extend(["makedirs", "removedirs", "renames"]) + +def walk(top, topdown=True, onerror=None, followlinks=False): + """Directory tree generator. + + For each directory in the directory tree rooted at top (including top + itself, but excluding '.' and '..'), yields a 3-tuple + + dirpath, dirnames, filenames + + dirpath is a string, the path to the directory. dirnames is a list of + the names of the subdirectories in dirpath (excluding '.' and '..'). + filenames is a list of the names of the non-directory files in dirpath. + Note that the names in the lists are just names, with no path components. + To get a full path (which begins with top) to a file or directory in + dirpath, do os.path.join(dirpath, name). + + If optional arg 'topdown' is true or not specified, the triple for a + directory is generated before the triples for any of its subdirectories + (directories are generated top down). If topdown is false, the triple + for a directory is generated after the triples for all of its + subdirectories (directories are generated bottom up). + + When topdown is true, the caller can modify the dirnames list in-place + (e.g., via del or slice assignment), and walk will only recurse into the + subdirectories whose names remain in dirnames; this can be used to prune + the search, or to impose a specific order of visiting. Modifying + dirnames when topdown is false is ineffective, since the directories in + dirnames have already been generated by the time dirnames itself is + generated. + + By default errors from the os.listdir() call are ignored. If + optional arg 'onerror' is specified, it should be a function; it + will be called with one argument, an os.error instance. It can + report the error to continue with the walk, or raise the exception + to abort the walk. Note that the filename is available as the + filename attribute of the exception object. + + By default, os.walk does not follow symbolic links to subdirectories on + systems that support them. In order to get this functionality, set the + optional argument 'followlinks' to true. + + Caution: if you pass a relative pathname for top, don't change the + current working directory between resumptions of walk. walk never + changes the current directory, and assumes that the client doesn't + either. + + Example: + + import os + from os.path import join, getsize + for root, dirs, files in os.walk('python/Lib/email'): + print root, "consumes", + print sum([getsize(join(root, name)) for name in files]), + print "bytes in", len(files), "non-directory files" + if 'CVS' in dirs: + dirs.remove('CVS') # don't visit CVS directories + """ + + from os.path import join, isdir, islink + + # We may not have read permission for top, in which case we can't + # get a list of the files the directory contains. os.path.walk + # always suppressed the exception then, rather than blow up for a + # minor reason when (say) a thousand readable directories are still + # left to visit. That logic is copied here. + try: + # Note that listdir and error are globals in this module due + # to earlier import-*. + names = listdir(top) + except error, err: + if onerror is not None: + onerror(err) + return + + dirs, nondirs = [], [] + for name in names: + if isdir(join(top, name)): + dirs.append(name) + else: + nondirs.append(name) + + if topdown: + yield top, dirs, nondirs + for name in dirs: + path = join(top, name) + if followlinks or not islink(path): + for x in walk(path, topdown, onerror, followlinks): + yield x + if not topdown: + yield top, dirs, nondirs + +__all__.append("walk") + +# Make sure os.environ exists, at least +try: + environ +except NameError: + environ = {} + +def execl(file, *args): + """execl(file, *args) + + Execute the executable file with argument list args, replacing the + current process. """ + execv(file, args) + +def execle(file, *args): + """execle(file, *args, env) + + Execute the executable file with argument list args and + environment env, replacing the current process. """ + env = args[-1] + execve(file, args[:-1], env) + +def execlp(file, *args): + """execlp(file, *args) + + Execute the executable file (which is searched for along $PATH) + with argument list args, replacing the current process. """ + execvp(file, args) + +def execlpe(file, *args): + """execlpe(file, *args, env) + + Execute the executable file (which is searched for along $PATH) + with argument list args and environment env, replacing the current + process. """ + env = args[-1] + execvpe(file, args[:-1], env) + +def execvp(file, args): + """execp(file, args) + + Execute the executable file (which is searched for along $PATH) + with argument list args, replacing the current process. + args may be a list or tuple of strings. """ + _execvpe(file, args) + +def execvpe(file, args, env): + """execvpe(file, args, env) + + Execute the executable file (which is searched for along $PATH) + with argument list args and environment env , replacing the + current process. + args may be a list or tuple of strings. """ + _execvpe(file, args, env) + +__all__.extend(["execl","execle","execlp","execlpe","execvp","execvpe"]) + +def _execvpe(file, args, env=None): + if env is not None: + func = execve + argrest = (args, env) + else: + func = execv + argrest = (args,) + env = environ + + head, tail = path.split(file) + if head: + func(file, *argrest) + return + if 'PATH' in env: + envpath = env['PATH'] + else: + envpath = defpath + PATH = envpath.split(pathsep) + saved_exc = None + saved_tb = None + for dir in PATH: + fullname = path.join(dir, file) + try: + func(fullname, *argrest) + except error, e: + tb = sys.exc_info()[2] + if (e.errno != errno.ENOENT and e.errno != errno.ENOTDIR + and saved_exc is None): + saved_exc = e + saved_tb = tb + if saved_exc: + raise error, saved_exc, saved_tb + raise error, e, tb + +# Change environ to automatically call putenv() if it exists +try: + # This will fail if there's no putenv + putenv +except NameError: + pass +else: + import UserDict + + # Fake unsetenv() for Windows + # not sure about os2 here but + # I'm guessing they are the same. + + if name in ('os2', 'nt'): + def unsetenv(key): + putenv(key, "") + + if name == "riscos": + # On RISC OS, all env access goes through getenv and putenv + from riscosenviron import _Environ + elif name in ('os2', 'nt'): # Where Env Var Names Must Be UPPERCASE + # But we store them as upper case + class _Environ(UserDict.IterableUserDict): + def __init__(self, environ): + UserDict.UserDict.__init__(self) + data = self.data + for k, v in environ.items(): + data[k.upper()] = v + def __setitem__(self, key, item): + putenv(key, item) + self.data[key.upper()] = item + def __getitem__(self, key): + return self.data[key.upper()] + try: + unsetenv + except NameError: + def __delitem__(self, key): + del self.data[key.upper()] + else: + def __delitem__(self, key): + unsetenv(key) + del self.data[key.upper()] + def clear(self): + for key in self.data.keys(): + unsetenv(key) + del self.data[key] + def pop(self, key, *args): + unsetenv(key) + return self.data.pop(key.upper(), *args) + def has_key(self, key): + return key.upper() in self.data + def __contains__(self, key): + return key.upper() in self.data + def get(self, key, failobj=None): + return self.data.get(key.upper(), failobj) + def update(self, dict=None, **kwargs): + if dict: + try: + keys = dict.keys() + except AttributeError: + # List of (key, value) + for k, v in dict: + self[k] = v + else: + # got keys + # cannot use items(), since mappings + # may not have them. + for k in keys: + self[k] = dict[k] + if kwargs: + self.update(kwargs) + def copy(self): + return dict(self) + + else: # Where Env Var Names Can Be Mixed Case + class _Environ(UserDict.IterableUserDict): + def __init__(self, environ): + UserDict.UserDict.__init__(self) + self.data = environ + def __setitem__(self, key, item): + putenv(key, item) + self.data[key] = item + def update(self, dict=None, **kwargs): + if dict: + try: + keys = dict.keys() + except AttributeError: + # List of (key, value) + for k, v in dict: + self[k] = v + else: + # got keys + # cannot use items(), since mappings + # may not have them. + for k in keys: + self[k] = dict[k] + if kwargs: + self.update(kwargs) + try: + unsetenv + except NameError: + pass + else: + def __delitem__(self, key): + unsetenv(key) + del self.data[key] + def clear(self): + for key in self.data.keys(): + unsetenv(key) + del self.data[key] + def pop(self, key, *args): + unsetenv(key) + return self.data.pop(key, *args) + def copy(self): + return dict(self) + + + environ = _Environ(environ) + +def getenv(key, default=None): + """Get an environment variable, return None if it doesn't exist. + The optional second argument can specify an alternate default.""" + return environ.get(key, default) +__all__.append("getenv") + +def _exists(name): + try: + eval(name) + return True + except NameError: + return False + +# Supply spawn*() (probably only for Unix) +if _exists("fork") and not _exists("spawnv") and _exists("execv"): + + P_WAIT = 0 + P_NOWAIT = P_NOWAITO = 1 + + # XXX Should we support P_DETACH? I suppose it could fork()**2 + # and close the std I/O streams. Also, P_OVERLAY is the same + # as execv*()? + + def _spawnvef(mode, file, args, env, func): + # Internal helper; func is the exec*() function to use + pid = fork() + if not pid: + # Child + try: + if env is None: + func(file, args) + else: + func(file, args, env) + except: + _exit(127) + else: + # Parent + if mode == P_NOWAIT: + return pid # Caller is responsible for waiting! + while 1: + wpid, sts = waitpid(pid, 0) + if WIFSTOPPED(sts): + continue + elif WIFSIGNALED(sts): + return -WTERMSIG(sts) + elif WIFEXITED(sts): + return WEXITSTATUS(sts) + else: + raise error, "Not stopped, signaled or exited???" + + def spawnv(mode, file, args): + """spawnv(mode, file, args) -> integer + +Execute file with arguments from args in a subprocess. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. """ + return _spawnvef(mode, file, args, None, execv) + + def spawnve(mode, file, args, env): + """spawnve(mode, file, args, env) -> integer + +Execute file with arguments from args in a subprocess with the +specified environment. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. """ + return _spawnvef(mode, file, args, env, execve) + + # Note: spawnvp[e] is't currently supported on Windows + + def spawnvp(mode, file, args): + """spawnvp(mode, file, args) -> integer + +Execute file (which is looked for along $PATH) with arguments from +args in a subprocess. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. """ + return _spawnvef(mode, file, args, None, execvp) + + def spawnvpe(mode, file, args, env): + """spawnvpe(mode, file, args, env) -> integer + +Execute file (which is looked for along $PATH) with arguments from +args in a subprocess with the supplied environment. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. """ + return _spawnvef(mode, file, args, env, execvpe) + +if _exists("spawnv"): + # These aren't supplied by the basic Windows code + # but can be easily implemented in Python + + def spawnl(mode, file, *args): + """spawnl(mode, file, *args) -> integer + +Execute file with arguments from args in a subprocess. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. """ + return spawnv(mode, file, args) + + def spawnle(mode, file, *args): + """spawnle(mode, file, *args, env) -> integer + +Execute file with arguments from args in a subprocess with the +supplied environment. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. """ + env = args[-1] + return spawnve(mode, file, args[:-1], env) + + + __all__.exte... [truncated message content] |
From: <pj...@us...> - 2009-10-19 21:26:28
|
Revision: 6872 http://jython.svn.sourceforge.net/jython/?rev=6872&view=rev Author: pjenvey Date: 2009-10-19 21:26:09 +0000 (Mon, 19 Oct 2009) Log Message: ----------- bring in constantine 0.6 release, for OpenFlags Modified Paths: -------------- trunk/jython/build.xml Added Paths: ----------- trunk/jython/extlibs/constantine.jar Removed Paths: ------------- trunk/jython/extlibs/constantine-0.4.jar Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2009-10-19 04:56:15 UTC (rev 6871) +++ trunk/jython/build.xml 2009-10-19 21:26:09 UTC (rev 6872) @@ -189,7 +189,7 @@ <pathelement path="${extlibs.dir}/asm-3.1.jar" /> <pathelement path="${extlibs.dir}/asm-commons-3.1.jar" /> - <pathelement path="${extlibs.dir}/constantine-0.4.jar" /> + <pathelement path="${extlibs.dir}/constantine.jar" /> <pathelement path="${extlibs.dir}/jna.jar"/> <pathelement path="${extlibs.dir}/jna-posix.jar"/> </path> @@ -573,7 +573,7 @@ <zipfileset src="extlibs/jna-posix.jar"/> <!-- <rule pattern="com.sun.jna.**" result="org.python.jna.@1"/> --> <rule pattern="org.jruby.ext.posix.**" result="org.python.posix.@1"/> - <zipfileset src="extlibs/constantine-0.4.jar"/> + <zipfileset src="extlibs/constantine.jar"/> <rule pattern="com.kenai.constantine.**" result="org.python.constantine.@1"/> <zipfileset src="extlibs/xercesImpl-2.9.1.jar" excludes="META-INF/services/*"/> <rule pattern="org.apache.xml.**" result="org.python.apache.xml.@1"/> Deleted: trunk/jython/extlibs/constantine-0.4.jar =================================================================== (Binary files differ) Added: trunk/jython/extlibs/constantine.jar =================================================================== (Binary files differ) Property changes on: trunk/jython/extlibs/constantine.jar ___________________________________________________________________ Added: svn:mime-type + application/octet-stream This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-19 04:56:33
|
Revision: 6871 http://jython.svn.sourceforge.net/jython/?rev=6871&view=rev Author: pjenvey Date: 2009-10-19 04:56:15 +0000 (Mon, 19 Oct 2009) Log Message: ----------- two exceptions walk into a bar. ouch! Modified Paths: -------------- trunk/jython/Lib/os.py Modified: trunk/jython/Lib/os.py =================================================================== --- trunk/jython/Lib/os.py 2009-10-18 18:59:19 UTC (rev 6870) +++ trunk/jython/Lib/os.py 2009-10-19 04:56:15 UTC (rev 6871) @@ -478,8 +478,6 @@ return stat_result.from_jnastat(_posix.stat(abs_path)) except NotImplementedError: pass - except: - raise f = File(abs_path) if not f.exists(): raise OSError(errno.ENOENT, strerror(errno.ENOENT), path) @@ -506,8 +504,6 @@ return stat_result.from_jnastat(_posix.lstat(abs_path)) except NotImplementedError: pass - except: - raise f = File(sys.getPath(path)) # XXX: jna-posix implements similar link detection in # JavaFileStat.calculateSymlink, fallback to that instead when not This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-18 18:59:38
|
Revision: 6870 http://jython.svn.sourceforge.net/jython/?rev=6870&view=rev Author: pjenvey Date: 2009-10-18 18:59:19 +0000 (Sun, 18 Oct 2009) Log Message: ----------- cache TYPE Modified Paths: -------------- trunk/jython/src/org/python/core/PyCell.java Modified: trunk/jython/src/org/python/core/PyCell.java =================================================================== --- trunk/jython/src/org/python/core/PyCell.java 2009-10-17 17:07:38 UTC (rev 6869) +++ trunk/jython/src/org/python/core/PyCell.java 2009-10-18 18:59:19 UTC (rev 6870) @@ -6,16 +6,21 @@ /** * The Python cell type. - * - * Cells are used to implement variables referenced by multiple - * scopes. + * + * Cells are used to implement variables referenced by multiple scopes. */ @ExposedType(name = "cell", isBaseType = false) public class PyCell extends PyObject { + public static final PyType TYPE = PyType.fromClass(PyCell.class); + /** The underlying content of the cell, or null. */ public PyObject ob_ref; + public PyCell() { + super(TYPE); + } + @ExposedGet(name = "cell_contents") public PyObject getCellContents() { if (ob_ref == null) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-17 17:07:59
|
Revision: 6869 http://jython.svn.sourceforge.net/jython/?rev=6869&view=rev Author: pjenvey Date: 2009-10-17 17:07:38 +0000 (Sat, 17 Oct 2009) Log Message: ----------- expose PyFastSequenceIter and avoid PyType.fromClass during its construction Modified Paths: -------------- trunk/jython/CoreExposed.includes trunk/jython/src/org/python/core/PyFastSequenceIter.java Modified: trunk/jython/CoreExposed.includes =================================================================== --- trunk/jython/CoreExposed.includes 2009-10-17 16:57:13 UTC (rev 6868) +++ trunk/jython/CoreExposed.includes 2009-10-17 17:07:38 UTC (rev 6869) @@ -15,6 +15,7 @@ org/python/core/PyDictProxy.class org/python/core/PyEnumerate.class org/python/core/PyEllipsis.class +org/python/core/PyFastSequenceIter.class org/python/core/PyFile.class org/python/core/PyFloat.class org/python/core/PyFrame.class Modified: trunk/jython/src/org/python/core/PyFastSequenceIter.java =================================================================== --- trunk/jython/src/org/python/core/PyFastSequenceIter.java 2009-10-17 16:57:13 UTC (rev 6868) +++ trunk/jython/src/org/python/core/PyFastSequenceIter.java 2009-10-17 17:07:38 UTC (rev 6869) @@ -1,19 +1,32 @@ /* Copyright (c) Jython Developers */ package org.python.core; +import org.python.expose.ExposedMethod; +import org.python.expose.ExposedType; + /** * Sequence iterator specialized for accessing the underlying sequence directly. */ +@ExposedType(name = "fastsequenceiterator", base = PyObject.class, isBaseType = false) public class PyFastSequenceIter extends PyIterator { + public static final PyType TYPE = PyType.fromClass(PyFastSequenceIter.class); + private PySequence seq; - private int index = 0; + private int index; public PyFastSequenceIter(PySequence seq) { + super(TYPE); this.seq = seq; } + @ExposedMethod(doc = "x.next() -> the next value, or raise StopIteration") + final PyObject fastsequenceiterator_next() { + return super.next(); + } + + @Override public PyObject __iternext__() { if (seq == null) { return null; @@ -22,13 +35,14 @@ PyObject result; try { result = seq.seq___finditem__(index++); - } catch (PyException exc) { - if (exc.match(Py.StopIteration)) { + } catch (PyException pye) { + if (pye.match(Py.StopIteration)) { seq = null; return null; } - throw exc; + throw pye; } + if (result == null) { seq = null; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-17 16:57:31
|
Revision: 6868 http://jython.svn.sourceforge.net/jython/?rev=6868&view=rev Author: pjenvey Date: 2009-10-17 16:57:13 +0000 (Sat, 17 Oct 2009) Log Message: ----------- hardcode the __new__ descriptors' __doc__ Modified Paths: -------------- trunk/jython/src/org/python/core/PyNewWrapper.java Modified: trunk/jython/src/org/python/core/PyNewWrapper.java =================================================================== --- trunk/jython/src/org/python/core/PyNewWrapper.java 2009-10-17 16:10:18 UTC (rev 6867) +++ trunk/jython/src/org/python/core/PyNewWrapper.java 2009-10-17 16:57:13 UTC (rev 6868) @@ -19,6 +19,7 @@ public PyNewWrapper(PyType type, String name, int minargs, int maxargs) { super(type, new DefaultInfo(name, minargs, maxargs)); for_type = (PyType)getSelf(); + doc = BuiltinDocs.type___new___doc; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <am...@us...> - 2009-10-17 16:10:25
|
Revision: 6867 http://jython.svn.sourceforge.net/jython/?rev=6867&view=rev Author: amak Date: 2009-10-17 16:10:18 +0000 (Sat, 17 Oct 2009) Log Message: ----------- Adding a sample config value for load_site_packages. Modified Paths: -------------- trunk/jython/Demo/modjy_webapp/WEB-INF/web.xml Modified: trunk/jython/Demo/modjy_webapp/WEB-INF/web.xml =================================================================== --- trunk/jython/Demo/modjy_webapp/WEB-INF/web.xml 2009-10-17 16:03:45 UTC (rev 6866) +++ trunk/jython/Demo/modjy_webapp/WEB-INF/web.xml 2009-10-17 16:10:18 UTC (rev 6867) @@ -6,7 +6,7 @@ <display-name>modjy demo application</display-name> <description> - modjy WSGI demo application + modjy WSGI demo application </description> <servlet> @@ -15,58 +15,67 @@ <init-param> <param-name>python.home</param-name> <param-value>C:/jython2.5</param-value> - </init-param> -<!-- - There are two different ways you can specify an application to modjy - 1. Using the app_import_name mechanism - 2. Using a combination of app_directory/app_filename/app_callable_name - Examples of both are given below - See the documenation for more details. + </init-param> +<!-- + There are two different ways you can specify an application to modjy + 1. Using the app_import_name mechanism + 2. Using a combination of app_directory/app_filename/app_callable_name + Examples of both are given below + See the documenation for more details. http://modjy.xhaus.com/locating.html#locating_callables ---> -<!-- - This is the app_import_name mechanism. If you specify a value - for this variable, then it will take precedence over the other mechanism +--> +<!-- + This is the app_import_name mechanism. If you specify a value + for this variable, then it will take precedence over the other mechanism <init-param> <param-name>app_import_name</param-name> <param-value>my_wsgi_module.my_handler_class().handler_method</param-value> - </init-param> + </init-param> --> -<!-- - And this is the app_directory/app_filename/app_callable_name combo - The defaults for these three variables are ""/application.py/handler - So if you specify no values at all for any of app_* variables, then modjy - will by default look for "handler" in "application.py" in the servlet - context root. +<!-- + And this is the app_directory/app_filename/app_callable_name combo + The defaults for these three variables are ""/application.py/handler + So if you specify no values at all for any of app_* variables, then modjy + will by default look for "handler" in "application.py" in the servlet + context root. <init-param> <param-name>app_directory</param-name> <param-value>some_sub_directory</param-value> - </init-param> + </init-param> --> <init-param> <param-name>app_filename</param-name> <param-value>demo_app.py</param-value> </init-param> -<!-- - Supply a value for this parameter if you want your application - callable to have a different name than the default. +<!-- + Supply a value for this parameter if you want your application + callable to have a different name than the default. <init-param> <param-name>app_callable_name</param-name> <param-value>my_handler_func</param-value> </init-param> ---> - <!-- Do you want application callables to be cached? --> +--> + <!-- Do you want application callables to be cached? --> <init-param> <param-name>cache_callables</param-name> <param-value>1</param-value> - </init-param> - <!-- Should the application be reloaded if it's .py file changes? --> + </init-param> + <!-- Should the application be reloaded if it's .py file changes? --> <!-- Does not work with the app_import_name mechanism --> <init-param> <param-name>reload_on_mod</param-name> <param-value>1</param-value> </init-param> + <!-- + Is site-packages to be loaded through imp.load("site")? + Same as -S option to command line interpreter + --> <init-param> + <param-name>load_site_packages</param-name> + <param-value>1</param-value> +<!-- <param-value>0</param-value> --> + </init-param> + <init-param> <param-name>log_level</param-name> <param-value>debug</param-value> <!-- <param-value>info</param-value> --> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <am...@us...> - 2009-10-17 16:03:59
|
Revision: 6866 http://jython.svn.sourceforge.net/jython/?rev=6866&view=rev Author: amak Date: 2009-10-17 16:03:45 +0000 (Sat, 17 Oct 2009) Log Message: ----------- Fixing a previously unnoticed bug where a relative value for "python.home" was not being treated relative to the context root and should have been. Modified Paths: -------------- trunk/jython/src/com/xhaus/modjy/ModjyJServlet.java trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestBase.java Modified: trunk/jython/src/com/xhaus/modjy/ModjyJServlet.java =================================================================== --- trunk/jython/src/com/xhaus/modjy/ModjyJServlet.java 2009-10-17 02:11:46 UTC (rev 6865) +++ trunk/jython/src/com/xhaus/modjy/ModjyJServlet.java 2009-10-17 16:03:45 UTC (rev 6866) @@ -52,6 +52,8 @@ protected final static String LOAD_SITE_PACKAGES_PARAM = "load_site_packages"; + protected final static String PYTHON_HOME_PARAM = "python.home"; + protected PythonInterpreter interp; protected HttpServlet modjyServlet; @@ -78,6 +80,14 @@ String name = (String)e.nextElement(); props.put(name, getInitParameter(name)); } + // Check if python home is relative, in which case find it in the servlet context + String pythonHomeString = props.getProperty(PYTHON_HOME_PARAM); + if (pythonHomeString != null) { + File pythonHome = new File(pythonHomeString); + if (!pythonHome.isAbsolute()) + pythonHomeString = context.getRealPath(pythonHomeString); + props.setProperty(PYTHON_HOME_PARAM, pythonHomeString); + } return props; } @@ -101,7 +111,7 @@ interp.exec("from modjy.modjy import " + MODJY_PYTHON_CLASSNAME); } catch (PyException ix) { throw new ServletException("Unable to import '" + MODJY_PYTHON_CLASSNAME - + "': maybe you need to set the 'python.home' parameter?", ix); + + "': maybe you need to set the '" + PYTHON_HOME_PARAM + "' parameter?", ix); } PyObject pyServlet = ((PyType)interp.get(MODJY_PYTHON_CLASSNAME)).__call__(); Object temp = pyServlet.__tojava__(HttpServlet.class); Modified: trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestBase.java =================================================================== --- trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestBase.java 2009-10-17 02:11:46 UTC (rev 6865) +++ trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestBase.java 2009-10-17 16:03:45 UTC (rev 6866) @@ -195,13 +195,12 @@ String jythonHome = System.getProperty("JYTHON_HOME"); setRealPath(jythonHome, jythonHome); setRealPath("/WEB-INF/" + LIB_PYTHON_DIR, LIB_PYTHON_TEST_PATH); - setRealPath("/WEB-INF/lib/modjy.jar", "../modjy.jar"); setPythonHome(jythonHome); setAppDir(DEFAULT_APP_DIR); setAppFile(DEFAULT_APP_FILE); setAppName(DEFAULT_APP_NAME); setInitParameter("exc_handler", "testing"); -// dumpContextRealPaths(); +// dumpContextRealPaths(); } protected PyObject evalPythonString(String pyString) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-17 02:11:52
|
Revision: 6865 http://jython.svn.sourceforge.net/jython/?rev=6865&view=rev Author: pjenvey Date: 2009-10-17 02:11:46 +0000 (Sat, 17 Oct 2009) Log Message: ----------- fast path lists along with tuples and avoid the overhead of __len__'ing generators which can be a somewhat common make_array argument Modified Paths: -------------- trunk/jython/src/org/python/core/Py.java Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2009-10-16 05:51:46 UTC (rev 6864) +++ trunk/jython/src/org/python/core/Py.java 2009-10-17 02:11:46 UTC (rev 6865) @@ -1904,23 +1904,29 @@ } } - static PyObject[] make_array(PyObject o) { - if (o instanceof PyTuple) { - return ((PyTuple) o).getArray(); + static PyObject[] make_array(PyObject iterable) { + // Special-case the common tuple and list cases, for efficiency + if (iterable instanceof PySequenceList) { + return ((PySequenceList) iterable).getArray(); } - // Guess result size and allocate space. + + // Guess result size and allocate space. The typical make_array arg supports + // __len__, with one exception being generators, so avoid the overhead of an + // exception from __len__ in their case int n = 10; - try { - n = o.__len__(); - } catch (PyException exc) { + if (!(iterable instanceof PyGenerator)) { + try { + n = iterable.__len__(); + } catch (PyException pye) { + // ok + } } List<PyObject> objs = new ArrayList<PyObject>(n); - for (PyObject item : o.asIterable()) { + for (PyObject item : iterable.asIterable()) { objs.add(item); } - PyObject dest[] = new PyObject[0]; - return (objs.toArray(dest)); + return objs.toArray(Py.EmptyObjects); } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-16 05:51:52
|
Revision: 6864 http://jython.svn.sourceforge.net/jython/?rev=6864&view=rev Author: pjenvey Date: 2009-10-16 05:51:46 +0000 (Fri, 16 Oct 2009) Log Message: ----------- The GC thread should be able to safely create GeneratorExits now that PyExceptions no longer create tracebacks when constructed (and so don't immediately need a frame on hand). this speeds up generator construction Modified Paths: -------------- trunk/jython/src/org/python/core/PyGenerator.java Modified: trunk/jython/src/org/python/core/PyGenerator.java =================================================================== --- trunk/jython/src/org/python/core/PyGenerator.java 2009-10-16 03:34:01 UTC (rev 6863) +++ trunk/jython/src/org/python/core/PyGenerator.java 2009-10-16 05:51:46 UTC (rev 6864) @@ -16,19 +16,12 @@ @ExposedGet protected boolean gi_running; - private PyException generatorExit; - private PyObject closure; public PyGenerator(PyFrame frame, PyObject closure) { super(TYPE); gi_frame = frame; this.closure = closure; - - // Create an exception instance while we have a frame to create it from. When the GC runs it - // doesn't have any associated thread state. this is necessary for finalize calling close on - // the generator - generatorExit = Py.makeException(Py.GeneratorExit); } public PyObject send(PyObject value) { @@ -68,7 +61,7 @@ @ExposedMethod final PyObject generator_close() { try { - raiseException(generatorExit); + raiseException(Py.makeException(Py.GeneratorExit)); throw Py.RuntimeError("generator ignored GeneratorExit"); } catch (PyException e) { if (!(e.type == Py.StopIteration || e.type == Py.GeneratorExit)) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-16 03:34:18
|
Revision: 6863 http://jython.svn.sourceforge.net/jython/?rev=6863&view=rev Author: pjenvey Date: 2009-10-16 03:34:01 +0000 (Fri, 16 Oct 2009) Log Message: ----------- make the exposed methods final, cleanup Modified Paths: -------------- trunk/jython/src/org/python/core/PyGenerator.java Modified: trunk/jython/src/org/python/core/PyGenerator.java =================================================================== --- trunk/jython/src/org/python/core/PyGenerator.java 2009-10-16 02:41:41 UTC (rev 6862) +++ trunk/jython/src/org/python/core/PyGenerator.java 2009-10-16 03:34:01 UTC (rev 6863) @@ -1,3 +1,4 @@ +/* Copyright (c) Jython Developers */ package org.python.core; import org.python.expose.ExposedGet; @@ -30,8 +31,12 @@ generatorExit = Py.makeException(Py.GeneratorExit); } + public PyObject send(PyObject value) { + return generator_send(value); + } + @ExposedMethod - public PyObject send(PyObject value) { + final PyObject generator_send(PyObject value) { if (gi_frame == null) { throw Py.StopIteration(""); } @@ -42,8 +47,12 @@ return next(); } + public PyObject throw$(PyObject type, PyObject value, PyObject tb) { + return generator_throw$(type, value, tb); + } + @ExposedMethod(names="throw", defaults={"null", "null"}) - public PyObject throw$(PyObject type, PyObject value, PyObject tb) { + final PyObject generator_throw$(PyObject type, PyObject value, PyObject tb) { if (tb == Py.None) { tb = null; } else if (tb != null && !(tb instanceof PyTraceback)) { @@ -52,8 +61,12 @@ return raiseException(Py.makeException(type, value, tb)); } + public PyObject close() { + return generator_close(); + } + @ExposedMethod - public PyObject close() { + final PyObject generator_close() { try { raiseException(generatorExit); throw Py.RuntimeError("generator ignored GeneratorExit"); @@ -66,14 +79,22 @@ } @Override + public PyObject next() { + return generator_next(); + } + @ExposedMethod(doc="x.next() -> the next value, or raise StopIteration") - public PyObject next() { + final PyObject generator_next() { return super.next(); } @Override + public PyObject __iter__() { + return generator___iter__(); + } + @ExposedMethod - public PyObject __iter__() { + final PyObject generator___iter__() { return this; } @@ -87,37 +108,39 @@ @Override protected void finalize() throws Throwable { - if (gi_frame == null || gi_frame.f_lasti == -1) + if (gi_frame == null || gi_frame.f_lasti == -1) { return; + } try { close(); - } catch (PyException e) { + } catch (PyException pye) { // PEP 342 specifies that if an exception is raised by close, // we output to stderr and then forget about it; - String className = PyException.exceptionClassName(e.type); + String className = PyException.exceptionClassName(pye.type); int lastDot = className.lastIndexOf('.'); if (lastDot != -1) { className = className.substring(lastDot + 1); } - String msg = String.format("Exception %s: %s in %s", className, e.value.__repr__() - .toString(), __repr__().toString()); + String msg = String.format("Exception %s: %s in %s", className, pye.value.__repr__(), + __repr__()); Py.println(Py.getSystemState().stderr, Py.newString(msg)); - } catch (Throwable e) { + } catch (Throwable t) { // but we currently ignore any Java exception completely. perhaps we // can also output something meaningful too? } finally { super.finalize(); } } - + @Override public PyObject __iternext__() { return __iternext__(Py.getThreadState()); } public PyObject __iternext__(ThreadState state) { - if (gi_running) + if (gi_running) { throw Py.ValueError("generator already executing"); + } if (gi_frame == null) { return null; } @@ -130,12 +153,12 @@ PyObject result = null; try { result = gi_frame.f_code.call(state, gi_frame, closure); - } catch(PyException e) { - if (!(e.type == Py.StopIteration || e.type == Py.GeneratorExit)) { + } catch (PyException pye) { + if (!(pye.type == Py.StopIteration || pye.type == Py.GeneratorExit)) { gi_frame = null; - throw e; + throw pye; } else { - stopException = e; + stopException = pye; gi_frame = null; return null; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-16 02:41:48
|
Revision: 6862 http://jython.svn.sourceforge.net/jython/?rev=6862&view=rev Author: pjenvey Date: 2009-10-16 02:41:41 +0000 (Fri, 16 Oct 2009) Log Message: ----------- toArray arg can't be null Modified Paths: -------------- trunk/jython/src/org/python/core/PyList.java Modified: trunk/jython/src/org/python/core/PyList.java =================================================================== --- trunk/jython/src/org/python/core/PyList.java 2009-10-16 02:39:10 UTC (rev 6861) +++ trunk/jython/src/org/python/core/PyList.java 2009-10-16 02:41:41 UTC (rev 6862) @@ -978,8 +978,7 @@ @Override public synchronized PyObject[] getArray() { - PyObject a[] = null; - return list.toArray(a); + return list.toArray(Py.EmptyObjects); } @Override This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-16 02:39:29
|
Revision: 6861 http://jython.svn.sourceforge.net/jython/?rev=6861&view=rev Author: pjenvey Date: 2009-10-16 02:39:10 +0000 (Fri, 16 Oct 2009) Log Message: ----------- doc sets and BaseException Modified Paths: -------------- trunk/jython/Misc/make_pydocs.py trunk/jython/src/org/python/core/BuiltinDocs.java trunk/jython/src/org/python/core/PyBaseException.java trunk/jython/src/org/python/core/PyFrozenSet.java trunk/jython/src/org/python/core/PySet.java trunk/jython/src/org/python/core/exceptions.java Modified: trunk/jython/Misc/make_pydocs.py =================================================================== --- trunk/jython/Misc/make_pydocs.py 2009-10-15 19:34:31 UTC (rev 6860) +++ trunk/jython/Misc/make_pydocs.py 2009-10-16 02:39:10 UTC (rev 6861) @@ -53,6 +53,9 @@ complex, opt('bool'), classmethod, +set, +frozenset, +BaseException, #buffer, # + type(f), @@ -60,7 +63,6 @@ type(f.func_code), type(sys._getframe()), type(tb), -#type(slice), ] outfile = open("BuiltinDocs.java", "w") @@ -75,5 +77,3 @@ print_doc(outfile, obj, meth) print >> outfile, '}' - - Modified: trunk/jython/src/org/python/core/BuiltinDocs.java =================================================================== --- trunk/jython/src/org/python/core/BuiltinDocs.java 2009-10-15 19:34:31 UTC (rev 6860) +++ trunk/jython/src/org/python/core/BuiltinDocs.java 2009-10-16 02:39:10 UTC (rev 6861) @@ -2658,6 +2658,355 @@ public final static String classmethod___str___doc = "x.__str__() <==> str(x)"; + // Docs for <type 'set'> + public final static String set___and___doc = + "x.__and__(y) <==> x&y"; + + public final static String set___class___doc = + "type(object) -> the object's type\n" + + "type(name, bases, dict) -> a new type"; + + public final static String set___cmp___doc = + "x.__cmp__(y) <==> cmp(x,y)"; + + public final static String set___contains___doc = + "x.__contains__(y) <==> y in x."; + + public final static String set___delattr___doc = + "x.__delattr__('name') <==> del x.name"; + + public final static String set_doc = + "set(iterable) --> set object\n" + + "\n" + + "Build an unordered collection of unique elements."; + + public final static String set___eq___doc = + "x.__eq__(y) <==> x==y"; + + public final static String set___ge___doc = + "x.__ge__(y) <==> x>=y"; + + public final static String set___getattribute___doc = + "x.__getattribute__('name') <==> x.name"; + + public final static String set___gt___doc = + "x.__gt__(y) <==> x>y"; + + public final static String set___hash___doc = + "x.__hash__() <==> hash(x)"; + + public final static String set___iand___doc = + "x.__iand__(y) <==> x&y"; + + public final static String set___init___doc = + "x.__init__(...) initializes x; see x.__class__.__doc__ for signature"; + + public final static String set___ior___doc = + "x.__ior__(y) <==> x|y"; + + public final static String set___isub___doc = + "x.__isub__(y) <==> x-y"; + + public final static String set___iter___doc = + "x.__iter__() <==> iter(x)"; + + public final static String set___ixor___doc = + "x.__ixor__(y) <==> x^y"; + + public final static String set___le___doc = + "x.__le__(y) <==> x<=y"; + + public final static String set___len___doc = + "x.__len__() <==> len(x)"; + + public final static String set___lt___doc = + "x.__lt__(y) <==> x<y"; + + public final static String set___ne___doc = + "x.__ne__(y) <==> x!=y"; + + public final static String set___new___doc = + "T.__new__(S, ...) -> a new object with type S, a subtype of T"; + + public final static String set___or___doc = + "x.__or__(y) <==> x|y"; + + public final static String set___rand___doc = + "x.__rand__(y) <==> y&x"; + + public final static String set___reduce___doc = + "Return state information for pickling."; + + public final static String set___reduce_ex___doc = + "helper for pickle"; + + public final static String set___repr___doc = + "x.__repr__() <==> repr(x)"; + + public final static String set___ror___doc = + "x.__ror__(y) <==> y|x"; + + public final static String set___rsub___doc = + "x.__rsub__(y) <==> y-x"; + + public final static String set___rxor___doc = + "x.__rxor__(y) <==> y^x"; + + public final static String set___setattr___doc = + "x.__setattr__('name', value) <==> x.name = value"; + + public final static String set___str___doc = + "x.__str__() <==> str(x)"; + + public final static String set___sub___doc = + "x.__sub__(y) <==> x-y"; + + public final static String set___xor___doc = + "x.__xor__(y) <==> x^y"; + + public final static String set_add_doc = + "Add an element to a set.\n" + + "\n" + + "This has no effect if the element is already present."; + + public final static String set_clear_doc = + "Remove all elements from this set."; + + public final static String set_copy_doc = + "Return a shallow copy of a set."; + + public final static String set_difference_doc = + "Return the difference of two sets as a new set.\n" + + "\n" + + "(i.e. all elements that are in this set but not the other.)"; + + public final static String set_difference_update_doc = + "Remove all elements of another set from this set."; + + public final static String set_discard_doc = + "Remove an element from a set if it is a member.\n" + + "\n" + + "If the element is not a member, do nothing."; + + public final static String set_intersection_doc = + "Return the intersection of two sets as a new set.\n" + + "\n" + + "(i.e. all elements that are in both sets.)"; + + public final static String set_intersection_update_doc = + "Update a set with the intersection of itself and another."; + + public final static String set_issubset_doc = + "Report whether another set contains this set."; + + public final static String set_issuperset_doc = + "Report whether this set contains another set."; + + public final static String set_pop_doc = + "Remove and return an arbitrary set element."; + + public final static String set_remove_doc = + "Remove an element from a set; it must be a member.\n" + + "\n" + + "If the element is not a member, raise a KeyError."; + + public final static String set_symmetric_difference_doc = + "Return the symmetric difference of two sets as a new set.\n" + + "\n" + + "(i.e. all elements that are in exactly one of the sets.)"; + + public final static String set_symmetric_difference_update_doc = + "Update a set with the symmetric difference of itself and another."; + + public final static String set_union_doc = + "Return the union of two sets as a new set.\n" + + "\n" + + "(i.e. all elements that are in either set.)"; + + public final static String set_update_doc = + "Update a set with the union of itself and another."; + + // Docs for <type 'frozenset'> + public final static String frozenset___and___doc = + "x.__and__(y) <==> x&y"; + + public final static String frozenset___class___doc = + "type(object) -> the object's type\n" + + "type(name, bases, dict) -> a new type"; + + public final static String frozenset___cmp___doc = + "x.__cmp__(y) <==> cmp(x,y)"; + + public final static String frozenset___contains___doc = + "x.__contains__(y) <==> y in x."; + + public final static String frozenset___delattr___doc = + "x.__delattr__('name') <==> del x.name"; + + public final static String frozenset_doc = + "frozenset(iterable) --> frozenset object\n" + + "\n" + + "Build an immutable unordered collection of unique elements."; + + public final static String frozenset___eq___doc = + "x.__eq__(y) <==> x==y"; + + public final static String frozenset___ge___doc = + "x.__ge__(y) <==> x>=y"; + + public final static String frozenset___getattribute___doc = + "x.__getattribute__('name') <==> x.name"; + + public final static String frozenset___gt___doc = + "x.__gt__(y) <==> x>y"; + + public final static String frozenset___hash___doc = + "x.__hash__() <==> hash(x)"; + + public final static String frozenset___init___doc = + "x.__init__(...) initializes x; see x.__class__.__doc__ for signature"; + + public final static String frozenset___iter___doc = + "x.__iter__() <==> iter(x)"; + + public final static String frozenset___le___doc = + "x.__le__(y) <==> x<=y"; + + public final static String frozenset___len___doc = + "x.__len__() <==> len(x)"; + + public final static String frozenset___lt___doc = + "x.__lt__(y) <==> x<y"; + + public final static String frozenset___ne___doc = + "x.__ne__(y) <==> x!=y"; + + public final static String frozenset___new___doc = + "T.__new__(S, ...) -> a new object with type S, a subtype of T"; + + public final static String frozenset___or___doc = + "x.__or__(y) <==> x|y"; + + public final static String frozenset___rand___doc = + "x.__rand__(y) <==> y&x"; + + public final static String frozenset___reduce___doc = + "Return state information for pickling."; + + public final static String frozenset___reduce_ex___doc = + "helper for pickle"; + + public final static String frozenset___repr___doc = + "x.__repr__() <==> repr(x)"; + + public final static String frozenset___ror___doc = + "x.__ror__(y) <==> y|x"; + + public final static String frozenset___rsub___doc = + "x.__rsub__(y) <==> y-x"; + + public final static String frozenset___rxor___doc = + "x.__rxor__(y) <==> y^x"; + + public final static String frozenset___setattr___doc = + "x.__setattr__('name', value) <==> x.name = value"; + + public final static String frozenset___str___doc = + "x.__str__() <==> str(x)"; + + public final static String frozenset___sub___doc = + "x.__sub__(y) <==> x-y"; + + public final static String frozenset___xor___doc = + "x.__xor__(y) <==> x^y"; + + public final static String frozenset_copy_doc = + "Return a shallow copy of a set."; + + public final static String frozenset_difference_doc = + "Return the difference of two sets as a new set.\n" + + "\n" + + "(i.e. all elements that are in this set but not the other.)"; + + public final static String frozenset_intersection_doc = + "Return the intersection of two sets as a new set.\n" + + "\n" + + "(i.e. all elements that are in both sets.)"; + + public final static String frozenset_issubset_doc = + "Report whether another set contains this set."; + + public final static String frozenset_issuperset_doc = + "Report whether this set contains another set."; + + public final static String frozenset_symmetric_difference_doc = + "Return the symmetric difference of two sets as a new set.\n" + + "\n" + + "(i.e. all elements that are in exactly one of the sets.)"; + + public final static String frozenset_union_doc = + "Return the union of two sets as a new set.\n" + + "\n" + + "(i.e. all elements that are in either set.)"; + + // Docs for <type 'exceptions.BaseException'> + public final static String BaseException___class___doc = + "type(object) -> the object's type\n" + + "type(name, bases, dict) -> a new type"; + + public final static String BaseException___delattr___doc = + "x.__delattr__('name') <==> del x.name"; + + public final static String BaseException___dict___doc = + ""; + + public final static String BaseException_doc = + "Common base class for all exceptions"; + + public final static String BaseException___getattribute___doc = + "x.__getattribute__('name') <==> x.name"; + + public final static String BaseException___getitem___doc = + "x.__getitem__(y) <==> x[y]"; + + public final static String BaseException___getslice___doc = + "x.__getslice__(i, j) <==> x[i:j]\n" + + " \n" + + " Use of negative indices is not supported."; + + public final static String BaseException___hash___doc = + "x.__hash__() <==> hash(x)"; + + public final static String BaseException___init___doc = + "x.__init__(...) initializes x; see x.__class__.__doc__ for signature"; + + public final static String BaseException___new___doc = + "T.__new__(S, ...) -> a new object with type S, a subtype of T"; + + public final static String BaseException___reduce___doc = + ""; + + public final static String BaseException___reduce_ex___doc = + "helper for pickle"; + + public final static String BaseException___repr___doc = + "x.__repr__() <==> repr(x)"; + + public final static String BaseException___setattr___doc = + "x.__setattr__('name', value) <==> x.name = value"; + + public final static String BaseException___setstate___doc = + ""; + + public final static String BaseException___str___doc = + "x.__str__() <==> str(x)"; + + public final static String BaseException_args_doc = + ""; + + public final static String BaseException_message_doc = + "exception message"; + // Docs for <type 'function'> public final static String function___call___doc = "x.__call__(...) <==> x(...)"; Modified: trunk/jython/src/org/python/core/PyBaseException.java =================================================================== --- trunk/jython/src/org/python/core/PyBaseException.java 2009-10-15 19:34:31 UTC (rev 6860) +++ trunk/jython/src/org/python/core/PyBaseException.java 2009-10-16 02:39:10 UTC (rev 6861) @@ -12,18 +12,18 @@ * The base class for all standard Python exceptions. * */ -@ExposedType(name = "exceptions.BaseException") +@ExposedType(name = "exceptions.BaseException", doc = BuiltinDocs.BaseException_doc) public class PyBaseException extends PyObject { public static final PyType TYPE = PyType.fromClass(PyBaseException.class); /** Exception message. */ - @ExposedGet + @ExposedGet(doc = BuiltinDocs.BaseException_message_doc) @ExposedSet public PyObject message = Py.EmptyString; /** Exception's arguments. */ - @ExposedGet + @ExposedGet(doc = BuiltinDocs.BaseException_args_doc) public PyObject args = Py.EmptyTuple; /** Exception's underlying dictionary, lazily created. */ @@ -42,7 +42,7 @@ } @ExposedNew - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.BaseException___init___doc) final void BaseException___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser(getType().getName(), args, keywords, "args"); ap.noKeywords(); @@ -56,7 +56,7 @@ return BaseException___getitem__(index); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.BaseException___getitem___doc) final PyObject BaseException___getitem__(PyObject index) { return args.__getitem__(index); } @@ -65,7 +65,7 @@ return BaseException___getslice__(start, stop); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.BaseException___getslice___doc) final PyObject BaseException___getslice__(PyObject start, PyObject stop) { return args.__getslice__(start, stop); } @@ -75,7 +75,7 @@ return BaseException___reduce__(); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.BaseException___reduce___doc) final PyObject BaseException___reduce__() { if (__dict__ != null) { return new PyTuple(getType(), args, __dict__); @@ -88,7 +88,7 @@ return BaseException___setstate__(state); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.BaseException___setstate___doc) final PyObject BaseException___setstate__(PyObject state) { if (state != Py.None) { if (!(state instanceof PyStringMap) && !(state instanceof PyDictionary)) { @@ -120,7 +120,7 @@ BaseException___setattr__(name, value); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.BaseException___setattr___doc) final void BaseException___setattr__(String name, PyObject value) { ensureDict(); super.__setattr__(name, value); @@ -130,7 +130,7 @@ return __dict__; } - @ExposedGet(name = "__dict__") + @ExposedGet(name = "__dict__", doc = BuiltinDocs.BaseException___dict___doc) public PyObject getDict() { ensureDict(); return __dict__; @@ -154,7 +154,7 @@ return BaseException___str__(); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.BaseException___str___doc) final PyString BaseException___str__() { switch (args.__len__()) { case 0: @@ -171,7 +171,7 @@ return BaseException_toString(); } - @ExposedMethod(names = ("__repr__")) + @ExposedMethod(names = "__repr__", doc = BuiltinDocs.BaseException___repr___doc) final String BaseException_toString() { PyObject reprSuffix = args.__repr__(); String name = getType().fastGetName(); Modified: trunk/jython/src/org/python/core/PyFrozenSet.java =================================================================== --- trunk/jython/src/org/python/core/PyFrozenSet.java 2009-10-15 19:34:31 UTC (rev 6860) +++ trunk/jython/src/org/python/core/PyFrozenSet.java 2009-10-16 02:39:10 UTC (rev 6861) @@ -9,7 +9,7 @@ import org.python.expose.ExposedType; import org.python.expose.MethodType; -@ExposedType(name = "frozenset", base = PyObject.class) +@ExposedType(name = "frozenset", base = PyObject.class, doc = BuiltinDocs.frozenset_doc) public class PyFrozenSet extends BaseSet { public static final PyType TYPE = PyType.fromClass(PyFrozenSet.class); @@ -51,72 +51,72 @@ return fset; } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.frozenset___cmp___doc) final PyObject frozenset___cmp__(PyObject o) { return new PyInteger(baseset___cmp__(o)); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.frozenset___ne___doc) final PyObject frozenset___ne__(PyObject o) { return baseset___ne__(o); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.frozenset___eq___doc) final PyObject frozenset___eq__(PyObject o) { return baseset___eq__(o); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.frozenset___or___doc) final PyObject frozenset___or__(PyObject o) { return baseset___or__(o); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.frozenset___xor___doc) final PyObject frozenset___xor__(PyObject o) { return baseset___xor__(o); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.frozenset___sub___doc) final PyObject frozenset___sub__(PyObject o) { return baseset___sub__(o); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.frozenset___and___doc) final PyObject frozenset___and__(PyObject o) { return baseset___and__(o); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.frozenset___lt___doc) final PyObject frozenset___lt__(PyObject o) { return baseset___lt__(o); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.frozenset___gt___doc) final PyObject frozenset___gt__(PyObject o) { return baseset___gt__(o); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.frozenset___ge___doc) final PyObject frozenset___ge__(PyObject o) { return baseset___ge__(o); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.frozenset___le___doc) final PyObject frozenset___le__(PyObject o) { return baseset___le__(o); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.frozenset___iter___doc) final PyObject frozenset___iter__() { return baseset___iter__(); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.frozenset___contains___doc) final boolean frozenset___contains__(PyObject item) { return baseset___contains__(item); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.frozenset_copy_doc) final PyObject frozenset_copy() { if (getClass() == PyFrozenSet.class) { return this; @@ -125,52 +125,52 @@ return baseset_copy(); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.frozenset_union_doc) final PyObject frozenset_union(PyObject set) { return baseset_union(set); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.frozenset_difference_doc) final PyObject frozenset_difference(PyObject set) { return baseset_difference(set); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.frozenset_symmetric_difference_doc) final PyObject frozenset_symmetric_difference(PyObject set) { return baseset_symmetric_difference(set); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.frozenset_intersection_doc) final PyObject frozenset_intersection(PyObject set) { return baseset_intersection(set); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.frozenset_issubset_doc) final PyObject frozenset_issubset(PyObject set) { return baseset_issubset(set); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.frozenset_issuperset_doc) final PyObject frozenset_issuperset(PyObject set) { return baseset_issuperset(set); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.frozenset___len___doc) final int frozenset___len__() { return baseset___len__(); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.frozenset___reduce___doc) final PyObject frozenset___reduce__() { return baseset___reduce__(); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.frozenset___hash___doc) final int frozenset___hash__() { return _set.hashCode(); } - @ExposedMethod(names = "__repr__") + @ExposedMethod(names = "__repr__", doc = BuiltinDocs.frozenset___repr___doc) final String frozenset_toString() { return baseset_toString(); } Modified: trunk/jython/src/org/python/core/PySet.java =================================================================== --- trunk/jython/src/org/python/core/PySet.java 2009-10-15 19:34:31 UTC (rev 6860) +++ trunk/jython/src/org/python/core/PySet.java 2009-10-16 02:39:10 UTC (rev 6861) @@ -10,7 +10,7 @@ import org.python.expose.MethodType; import org.python.util.Generic; -@ExposedType(name = "set", base = PyObject.class) +@ExposedType(name = "set", base = PyObject.class, doc = BuiltinDocs.set_doc) public class PySet extends BaseSet { public static final PyType TYPE = PyType.fromClass(PySet.class); @@ -33,7 +33,7 @@ } @ExposedNew - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.set___init___doc) final void set___init__(PyObject[] args, String[] kwds) { int nargs = args.length - kwds.length; if (nargs > 1) { @@ -47,112 +47,112 @@ _update(args[0]); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.set___cmp___doc) final PyObject set___cmp__(PyObject o) { return new PyInteger(baseset___cmp__(o)); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.set___ne___doc) final PyObject set___ne__(PyObject o) { return baseset___ne__(o); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.set___eq___doc) final PyObject set___eq__(PyObject o) { return baseset___eq__(o); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.set___or___doc) final PyObject set___or__(PyObject o) { return baseset___or__(o); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.set___xor___doc) final PyObject set___xor__(PyObject o) { return baseset___xor__(o); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.set___sub___doc) final PyObject set___sub__(PyObject o) { return baseset___sub__(o); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.set___and___doc) final PyObject set___and__(PyObject o) { return baseset___and__(o); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.set___lt___doc) final PyObject set___lt__(PyObject o) { return baseset___lt__(o); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.set___gt___doc) final PyObject set___gt__(PyObject o) { return baseset___gt__(o); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.set___ge___doc) final PyObject set___ge__(PyObject o) { return baseset___ge__(o); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.set___le___doc) final PyObject set___le__(PyObject o) { return baseset___le__(o); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.set___iter___doc) final PyObject set___iter__() { return baseset___iter__(); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.set___contains___doc) final boolean set___contains__(PyObject item) { return baseset___contains__(item); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.set_copy_doc) final PyObject set_copy() { return baseset_copy(); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.set_union_doc) final PyObject set_union(PyObject set) { return baseset_union(set); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.set_difference_doc) final PyObject set_difference(PyObject set) { return baseset_difference(set); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.set_symmetric_difference_doc) final PyObject set_symmetric_difference(PyObject set) { return baseset_symmetric_difference(set); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.set_intersection_doc) final PyObject set_intersection(PyObject set) { return baseset_intersection(set); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.set_issubset_doc) final PyObject set_issubset(PyObject set) { return baseset_issubset(set); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.set_issuperset_doc) final PyObject set_issuperset(PyObject set) { return baseset_issuperset(set); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.set___len___doc) final int set___len__() { return baseset___len__(); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.set___reduce___doc) final PyObject set___reduce__() { return baseset___reduce__(); } @@ -161,7 +161,7 @@ return set___ior__(other); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.set___ior___doc) final PyObject set___ior__(PyObject other) { if (!(other instanceof BaseSet)) { return null; @@ -174,7 +174,7 @@ return set___ixor__(other); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.set___ixor___doc) final PyObject set___ixor__(PyObject other) { if (!(other instanceof BaseSet)) { return null; @@ -187,7 +187,7 @@ return set___iand__(other); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.set___iand___doc) final PyObject set___iand__(PyObject other) { if (!(other instanceof BaseSet)) { return null; @@ -200,7 +200,7 @@ return set___isub__(other); } - @ExposedMethod(type = MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.set___isub___doc) final PyObject set___isub__(PyObject other) { if (!(other instanceof BaseSet)) { return null; @@ -213,17 +213,17 @@ return set___hash__(); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.set___hash___doc) final int set___hash__() { throw Py.TypeError("set objects are unhashable"); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.set_add_doc) final void set_add(PyObject o) { _set.add(o); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.set_remove_doc) final void set_remove(PyObject o) { boolean b = false; try { @@ -237,7 +237,7 @@ } } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.set_discard_doc) final void set_discard(PyObject o) { try { _set.remove(o); @@ -247,7 +247,7 @@ } } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.set_pop_doc) final PyObject set_pop() { Iterator iterator = _set.iterator(); try { @@ -259,17 +259,17 @@ } } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.set_clear_doc) final void set_clear() { _set.clear(); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.set_update_doc) final void set_update(PyObject data) { _update(data); } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.set_intersection_update_doc) final void set_intersection_update(PyObject other) { if (other instanceof BaseSet) { __iand__(other); @@ -279,7 +279,7 @@ } } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.set_symmetric_difference_update_doc) final void set_symmetric_difference_update(PyObject other) { if (this == other) { set_clear(); @@ -296,7 +296,7 @@ } } - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.set_difference_update_doc) final void set_difference_update(PyObject other) { if (other instanceof BaseSet) { __isub__(other); @@ -309,7 +309,7 @@ } } - @ExposedMethod(names = "__repr__") + @ExposedMethod(names = "__repr__", doc = BuiltinDocs.set___repr___doc) final String set_toString() { return baseset_toString(); } Modified: trunk/jython/src/org/python/core/exceptions.java =================================================================== --- trunk/jython/src/org/python/core/exceptions.java 2009-10-15 19:34:31 UTC (rev 6860) +++ trunk/jython/src/org/python/core/exceptions.java 2009-10-16 02:39:10 UTC (rev 6861) @@ -41,9 +41,6 @@ } ts.frame = frame; - // XXX: - PyObject baseExcDict = PyBaseException.TYPE.fastGetDict(); - baseExcDict.__setitem__("__doc__", Py.newString("Common base class for all exceptions")); dict.__setitem__("BaseException", PyBaseException.TYPE); buildClass(dict, "KeyboardInterrupt", "BaseException", "Program interrupted by user."); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2009-10-15 19:34:42
|
Revision: 6860 http://jython.svn.sourceforge.net/jython/?rev=6860&view=rev Author: otmarhumbel Date: 2009-10-15 19:34:31 +0000 (Thu, 15 Oct 2009) Log Message: ----------- fixed javadoc warnings Modified Paths: -------------- trunk/jython/build.xml trunk/jython/src/org/python/modules/cPickle.java trunk/jython/src/org/python/modules/cStringIO.java trunk/jython/src/org/python/modules/itertools.java Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2009-10-15 17:40:22 UTC (rev 6859) +++ trunk/jython/build.xml 2009-10-15 19:34:31 UTC (rev 6860) @@ -640,6 +640,7 @@ <target name="javadoc" depends="compile"> <path id="javadoc.classpath"> <pathelement path="${java.class.path}" /> + <pathelement path="${compile.dir}" /> <path refid="main.classpath" /> </path> <javadoc sourcepath="${source.dir}" Modified: trunk/jython/src/org/python/modules/cPickle.java =================================================================== --- trunk/jython/src/org/python/modules/cPickle.java 2009-10-15 17:40:22 UTC (rev 6859) +++ trunk/jython/src/org/python/modules/cPickle.java 2009-10-15 19:34:31 UTC (rev 6860) @@ -548,7 +548,7 @@ * @param file a file-like object, can be a cStringIO.StringIO, * a PyFile or any python object which implements a * <i>write</i> method. The data will be written as text. - * @returns a new Pickler instance. + * @return a new Pickler instance. */ public static Pickler Pickler(PyObject file) { return new Pickler(file, 0); @@ -560,7 +560,7 @@ * a PyFile or any python object which implements a * <i>write</i> method. * @param protocol pickle protocol version (0 - text, 1 - pre-2.3 binary, 2 - 2.3) - * @returns a new Pickler instance. + * @return a new Pickler instance. */ public static Pickler Pickler(PyObject file, int protocol) { return new Pickler(file, protocol); @@ -572,7 +572,7 @@ * @param file a file-like object, can be a cStringIO.StringIO, * a PyFile or any python object which implements a * <i>read</i> and <i>readline</i> method. - * @returns a new Unpickler instance. + * @return a new Unpickler instance. */ public static Unpickler Unpickler(PyObject file) { return new Unpickler(file); @@ -586,7 +586,6 @@ * a PyFile or any python object which implements a * <i>write</i> method. The data will be written as * text. - * @returns a new Unpickler instance. */ public static void dump(PyObject object, PyObject file) { dump(object, file, 0); @@ -599,7 +598,6 @@ * a PyFile or any python object which implements a * <i>write</i> method. * @param protocol pickle protocol version (0 - text, 1 - pre-2.3 binary, 2 - 2.3) - * @returns a new Unpickler instance. */ public static void dump(PyObject object, PyObject file, int protocol) { new Pickler(file, protocol).dump(object); @@ -609,7 +607,7 @@ /** * Shorthand function which pickles and returns the string representation. * @param object a data object which should be pickled. - * @returns a string representing the pickled object. + * @return a string representing the pickled object. */ public static PyString dumps(PyObject object) { return dumps(object, 0); @@ -620,7 +618,7 @@ * Shorthand function which pickles and returns the string representation. * @param object a data object which should be pickled. * @param protocol pickle protocol version (0 - text, 1 - pre-2.3 binary, 2 - 2.3) - * @returns a string representing the pickled object. + * @return a string representing the pickled object. */ public static PyString dumps(PyObject object, int protocol) { cStringIO.StringIO file = cStringIO.StringIO(); @@ -635,7 +633,7 @@ * @param file a file-like object, can be a cStringIO.StringIO, * a PyFile or any python object which implements a * <i>read</i> and <i>readline</i> method. - * @returns a new object. + * @return a new object. */ public static Object load(PyObject file) { return new Unpickler(file).load(); @@ -647,7 +645,7 @@ * returns the new object. * @param str a strings which must contain a pickled object * representation. - * @returns a new object. + * @return a new object. */ public static Object loads(PyObject str) { cStringIO.StringIO file = cStringIO.StringIO(str.toString()); Modified: trunk/jython/src/org/python/modules/cStringIO.java =================================================================== --- trunk/jython/src/org/python/modules/cStringIO.java 2009-10-15 17:40:22 UTC (rev 6859) +++ trunk/jython/src/org/python/modules/cStringIO.java 2009-10-15 19:34:31 UTC (rev 6860) @@ -26,10 +26,6 @@ * @version cStringIO.java,v 1.10 1999/05/20 18:03:20 fb Exp */ public class cStringIO { - /** - * Create an empty StringIO object - * @return a new StringIO object. - */ // would be nicer if we directly imported from os, but crazy to do so // since in python code itself @@ -48,7 +44,7 @@ /** * Create a StringIO object, initialized by the value. - * @param buf The initial value. + * @param buffer The initial value. * @return a new StringIO object. */ public static StringIO StringIO(String buffer) { @@ -134,8 +130,11 @@ /** * Position the file pointer to the position in the . - * @param pos the position in the file. - * @param mode; 0=from the start, 1=relative, 2=from the end. + * + * @param pos + * the position in the file. + * @param mode + * 0=from the start, 1=relative, 2=from the end. */ public synchronized void seek(long pos, int mode) { _complain_ifclosed(); @@ -162,7 +161,7 @@ /** * Return the file position. - * @returns the position in the file. + * @return the position in the file. */ public synchronized int tell() { _complain_ifclosed(); @@ -174,7 +173,7 @@ /** * Read all data until EOF is reached. * An empty string is returned when EOF is encountered immediately. - * @returns A string containing the data. + * @return A string containing the data. */ public PyString read() { return read(-1); @@ -187,7 +186,7 @@ * reached. An empty string is returned when EOF is encountered * immediately. * @param size the number of characters to read. - * @returns A string containing the data read. + * @return A string containing the data read. */ public synchronized PyString read(long size) { @@ -212,7 +211,7 @@ * is kept in the string (but may be absent when a file ends with * an incomplete line). * An empty string is returned when EOF is hit immediately. - * @returns data from the file up to and including the newline. + * @return data from the file up to and including the newline. */ public PyString readline() { return readline(-1); @@ -226,7 +225,7 @@ * If the size argument is non-negative, it is a maximum byte count * (including the trailing newline) and an incomplete line may be * returned. - * @returns data from the file up to and including the newline. + * @return data from the file up to and including the newline. */ public synchronized PyString readline(long size) { _complain_ifclosed(); @@ -317,7 +316,7 @@ /** * Write a string to the file. - * @param s The data to write. + * @param obj The data to write. */ public void write(PyObject obj) { write(obj.toString()); Modified: trunk/jython/src/org/python/modules/itertools.java =================================================================== --- trunk/jython/src/org/python/modules/itertools.java 2009-10-15 17:40:22 UTC (rev 6859) +++ trunk/jython/src/org/python/modules/itertools.java 2009-10-15 19:34:31 UTC (rev 6860) @@ -354,16 +354,14 @@ } /** - * @see islice(PyObject PyObject iterable, PyObject startObj, PyObject - * stopObj, PyObject stepObj) startObj defaults to 0 and stepObj to 1 + * @see #islice(PyObject, PyObject, PyObject, PyObject) startObj defaults to 0 and stepObj to 1 */ public static PyIterator islice(PyObject iterable, PyObject stopObj) { return islice(iterable, new PyInteger(0), stopObj, new PyInteger(1)); } /** - * @see islice(PyObject PyObject iterable, PyObject startObj, PyObject stopObj, PyObject - * stepObj) stepObj defaults to 1 + * @see #islice(PyObject, PyObject, PyObject, PyObject) stepObj defaults to 1 */ public static PyIterator islice(PyObject iterable, PyObject start, PyObject stopObj) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <am...@us...> - 2009-10-15 17:40:30
|
Revision: 6859 http://jython.svn.sourceforge.net/jython/?rev=6859&view=rev Author: amak Date: 2009-10-15 17:40:22 +0000 (Thu, 15 Oct 2009) Log Message: ----------- Checking in support for loading site-packages, through the use of imp.load("site"). Controlled with a "load_site_packages" option, which defaults to true. Modified Paths: -------------- trunk/jython/src/com/xhaus/modjy/ModjyJServlet.java trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestBase.java trunk/jython/tests/modjy/test_apps_dir/lifecycle_tests.py Added Paths: ----------- trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestInterpreterLifecycle.java Removed Paths: ------------- trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestServletLifecycle.java Modified: trunk/jython/src/com/xhaus/modjy/ModjyJServlet.java =================================================================== --- trunk/jython/src/com/xhaus/modjy/ModjyJServlet.java 2009-10-14 06:54:56 UTC (rev 6858) +++ trunk/jython/src/com/xhaus/modjy/ModjyJServlet.java 2009-10-15 17:40:22 UTC (rev 6859) @@ -33,6 +33,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.python.core.imp; import org.python.core.Py; import org.python.core.PyException; import org.python.core.PyObject; @@ -49,6 +50,8 @@ protected final static String PTH_FILE_EXTENSION = ".pth"; + protected final static String LOAD_SITE_PACKAGES_PARAM = "load_site_packages"; + protected PythonInterpreter interp; protected HttpServlet modjyServlet; @@ -140,7 +143,7 @@ * sys.path 2. Process the WEB-INF/lib-python directory, if it exists * * @param interp - * - The PythinInterpreter used to service requests + * - The PythonInterpreter used to service requests * @param props * - The properties from which config options are found * @param systemState @@ -148,11 +151,27 @@ */ protected void setupEnvironment(PythonInterpreter interp, Properties props, - PySystemState systemState) { + PySystemState systemState) throws PyException { + checkSitePackages(props); processPythonLib(interp, systemState); } /** + * Check if the user has requested to initialise the jython installation "site-packages". + * + * @param props + * - The properties from which config options are found + */ + protected void checkSitePackages(Properties props) throws PyException { + String loadSitePackagesParam = props.getProperty(LOAD_SITE_PACKAGES_PARAM); + boolean loadSitePackages = true; + if (loadSitePackagesParam != null && loadSitePackagesParam.trim().compareTo("0") == 0) + loadSitePackages = false; + if (loadSitePackages) + imp.load("site"); + } + + /** * Do all processing in relation to the lib-python subdirectory of WEB-INF * * @param interp Modified: trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestBase.java =================================================================== --- trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestBase.java 2009-10-14 06:54:56 UTC (rev 6858) +++ trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestBase.java 2009-10-15 17:40:22 UTC (rev 6859) @@ -238,7 +238,7 @@ suite.addTestSuite(ModjyTestHeaders.class); suite.addTestSuite(ModjyTestContentHeaders.class); suite.addTestSuite(ModjyTestReturnIterable.class); - suite.addTestSuite(ModjyTestServletLifecycle.class); + suite.addTestSuite(ModjyTestInterpreterLifecycle.class); suite.addTestSuite(ModjyTestWebInf.class); suite.addTestSuite(ModjyTestWSGIStreams.class); suite.addTestSuite(PyServletTest.class); Copied: trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestInterpreterLifecycle.java (from rev 6842, trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestServletLifecycle.java) =================================================================== --- trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestInterpreterLifecycle.java (rev 0) +++ trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestInterpreterLifecycle.java 2009-10-15 17:40:22 UTC (rev 6859) @@ -0,0 +1,62 @@ +/*### +# +# Copyright Alan Kennedy. +# +# You may contact the copyright holder at this uri: +# +# http://www.xhaus.com/contact/modjy +# +# The licence under which this code is released is the Apache License v2.0. +# +# The terms and conditions of this license are listed in a file contained +# in the distribution that also contained this file, under the name +# LICENSE.txt. +# +# You may also read a copy of the license at the following web address. +# +# http://modjy.xhaus.com/LICENSE.txt +# +###*/ + +package com.xhaus.modjy; + +import javax.servlet.http.HttpServlet; + +public class ModjyTestInterpreterLifecycle extends ModjyTestBase { + + protected void lifecycleTestSetUp() throws Exception { + baseSetUp(); + setAppFile("lifecycle_tests.py"); + } + + public void testAtExitHandlersCalled() throws Exception { + System.setProperty("modjy", "here"); + lifecycleTestSetUp(); + createServlet(); + doGet(); + HttpServlet modjyServlet = getServlet(); + modjyServlet.destroy(); + assertEquals("gone", System.getProperty("modjy")); + } + + public void testSitePackagesLoaded() throws Exception { + for (int loadSitePackages = -1 ; loadSitePackages < 2 ; loadSitePackages++) { + lifecycleTestSetUp(); + setAppName("load_site_packages_test"); + String parameter, expectedResult; + if (loadSitePackages != -1) { + parameter = Integer.toString(loadSitePackages); + setInitParameter("load_site_packages", parameter); + expectedResult = parameter; + } else { + // Do not set the parameter, so we get default behaviour + expectedResult = "1"; + } + createServlet(); + doGet(); + String result = getOutput(); + assertEquals(expectedResult, result); + } + } + +} Property changes on: trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestInterpreterLifecycle.java ___________________________________________________________________ Added: svn:mergeinfo + /branches/jsr223/tests/modjy/java/com/xhaus/modjy/ModjyTestServletLifecycle.java:6285-6565 /branches/newstyle-java-types/tests/modjy/java/com/xhaus/modjy/ModjyTestServletLifecycle.java:5564-5663,5666-5729 Deleted: trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestServletLifecycle.java =================================================================== --- trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestServletLifecycle.java 2009-10-14 06:54:56 UTC (rev 6858) +++ trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestServletLifecycle.java 2009-10-15 17:40:22 UTC (rev 6859) @@ -1,42 +0,0 @@ -/*### -# -# Copyright Alan Kennedy. -# -# You may contact the copyright holder at this uri: -# -# http://www.xhaus.com/contact/modjy -# -# The licence under which this code is released is the Apache License v2.0. -# -# The terms and conditions of this license are listed in a file contained -# in the distribution that also contained this file, under the name -# LICENSE.txt. -# -# You may also read a copy of the license at the following web address. -# -# http://modjy.xhaus.com/LICENSE.txt -# -###*/ - -package com.xhaus.modjy; - -import javax.servlet.http.HttpServlet; - -public class ModjyTestServletLifecycle extends ModjyTestBase { - - protected void lifecycleTestSetUp() throws Exception { - baseSetUp(); - setAppFile("lifecycle_tests.py"); - } - - public void testAtExitHandlersCalled() throws Exception { - System.setProperty("modjy", "here"); - lifecycleTestSetUp(); - createServlet(); - doGet(); - HttpServlet modjyServlet = getServlet(); - modjyServlet.destroy(); - assertEquals("gone", System.getProperty("modjy")); - } - -} Modified: trunk/jython/tests/modjy/test_apps_dir/lifecycle_tests.py =================================================================== --- trunk/jython/tests/modjy/test_apps_dir/lifecycle_tests.py 2009-10-14 06:54:56 UTC (rev 6858) +++ trunk/jython/tests/modjy/test_apps_dir/lifecycle_tests.py 2009-10-15 17:40:22 UTC (rev 6859) @@ -29,6 +29,11 @@ atexit.register(exit_func) def lifecycle_test(environ, start_response): - writer = start_response("200 OK", []) - writer("Hello World!") - return [] + start_response("200 OK", []) + return ["Hello World!"] + +def load_site_packages_test(environ, start_response): + import sys + start_response("200 OK", []) + response = {True: '1', False: '0'}[sys.modules.has_key('site')] + return [response] This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-14 06:55:14
|
Revision: 6858 http://jython.svn.sourceforge.net/jython/?rev=6858&view=rev Author: pjenvey Date: 2009-10-14 06:54:56 +0000 (Wed, 14 Oct 2009) Log Message: ----------- fix the docstring test Modified Paths: -------------- trunk/jython/tests/java/org/python/expose/generate/TypeExposerTest.java Modified: trunk/jython/tests/java/org/python/expose/generate/TypeExposerTest.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/TypeExposerTest.java 2009-10-14 06:37:50 UTC (rev 6857) +++ trunk/jython/tests/java/org/python/expose/generate/TypeExposerTest.java 2009-10-14 06:54:56 UTC (rev 6858) @@ -20,9 +20,9 @@ assertEquals("simpleexposed", t.getName()); assertEquals(SimpleExposed.class, t.getTypeClass()); assertEquals(false, t.getIsBaseType()); + assertEquals("Docstring", t.getDoc()); PyType type = PyType.fromClass(SimpleExposed.class); PyObject dict = t.getDict(type); - assertEquals(dict.__finditem__("__doc__"), Py.newString("Docstring")); assertNotNull(dict.__finditem__("simple_method")); assertNotNull(dict.__finditem__("prefixed")); assertNotNull(dict.__finditem__("__str__")); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-14 06:37:57
|
Revision: 6857 http://jython.svn.sourceforge.net/jython/?rev=6857&view=rev Author: pjenvey Date: 2009-10-14 06:37:50 +0000 (Wed, 14 Oct 2009) Log Message: ----------- add classmethod docs Modified Paths: -------------- trunk/jython/src/org/python/core/PyClassMethodDescr.java trunk/jython/src/org/python/core/PyDictionary.java trunk/jython/src/org/python/core/PyFloat.java trunk/jython/src/org/python/expose/ExposedClassMethod.java Modified: trunk/jython/src/org/python/core/PyClassMethodDescr.java =================================================================== --- trunk/jython/src/org/python/core/PyClassMethodDescr.java 2009-10-14 06:02:01 UTC (rev 6856) +++ trunk/jython/src/org/python/core/PyClassMethodDescr.java 2009-10-14 06:37:50 UTC (rev 6857) @@ -1,5 +1,7 @@ +/* Copyright (c) Jython Developers */ package org.python.core; +import org.python.expose.ExposedGet; import org.python.expose.ExposedMethod; import org.python.expose.ExposedType; @@ -8,10 +10,11 @@ public static final PyType TYPE = PyType.fromClass(PyClassMethodDescr.class); - PyClassMethodDescr(PyType t, PyBuiltinCallable meth) { - super(t, meth); + PyClassMethodDescr(PyType type, PyBuiltinCallable meth) { + super(type, meth); } + @Override public PyObject __get__(PyObject obj, PyObject type) { return classmethod_descriptor___get__(obj, type); } @@ -33,4 +36,10 @@ checkGetterType((PyType)type); return meth.bind(type); } + + @Override + @ExposedGet(name = "__doc__") + public String getDoc() { + return super.getDoc(); + } } Modified: trunk/jython/src/org/python/core/PyDictionary.java =================================================================== --- trunk/jython/src/org/python/core/PyDictionary.java 2009-10-14 06:02:01 UTC (rev 6856) +++ trunk/jython/src/org/python/core/PyDictionary.java 2009-10-14 06:37:50 UTC (rev 6857) @@ -92,7 +92,7 @@ return dict_fromkeys(TYPE, keys, value); } - @ExposedClassMethod(defaults = "Py.None") + @ExposedClassMethod(defaults = "Py.None", doc = BuiltinDocs.dict_fromkeys_doc) final static PyObject dict_fromkeys(PyType type, PyObject keys, PyObject value) { PyObject d = type.__call__(); for (PyObject o : keys.asIterable()) { Modified: trunk/jython/src/org/python/core/PyFloat.java =================================================================== --- trunk/jython/src/org/python/core/PyFloat.java 2009-10-14 06:02:01 UTC (rev 6856) +++ trunk/jython/src/org/python/core/PyFloat.java 2009-10-14 06:37:50 UTC (rev 6857) @@ -647,7 +647,7 @@ public static volatile Format double_format = Format.BE; public static volatile Format float_format = Format.BE; - @ExposedClassMethod + @ExposedClassMethod(doc = BuiltinDocs.float___getformat___doc) public static String float___getformat__(PyType type, String typestr) { if ("double".equals(typestr)) { return double_format.format(); @@ -658,7 +658,7 @@ } } - @ExposedClassMethod + @ExposedClassMethod(doc = BuiltinDocs.float___setformat___doc) public static void float___setformat__(PyType type, String typestr, String format) { Format new_format = null; if (!"double".equals(typestr) && !"float".equals(typestr)) { Modified: trunk/jython/src/org/python/expose/ExposedClassMethod.java =================================================================== --- trunk/jython/src/org/python/expose/ExposedClassMethod.java 2009-10-14 06:02:01 UTC (rev 6856) +++ trunk/jython/src/org/python/expose/ExposedClassMethod.java 2009-10-14 06:37:50 UTC (rev 6857) @@ -22,4 +22,9 @@ * @return default arguments. Starts at the number of arguments - defaults.length. */ String[] defaults() default {}; + + /** + * Returns the __doc__ String for this method. + */ + String doc() default ""; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-14 06:02:21
|
Revision: 6856 http://jython.svn.sourceforge.net/jython/?rev=6856&view=rev Author: pjenvey Date: 2009-10-14 06:02:01 +0000 (Wed, 14 Oct 2009) Log Message: ----------- docs galore, enable test_descr.descrdoc Modified Paths: -------------- trunk/jython/Lib/test/test_descr.py trunk/jython/Misc/make_pydocs.py trunk/jython/src/org/python/core/BuiltinDocs.java trunk/jython/src/org/python/core/PyBaseString.java trunk/jython/src/org/python/core/PyBoolean.java trunk/jython/src/org/python/core/PyClassMethod.java trunk/jython/src/org/python/core/PyComplex.java trunk/jython/src/org/python/core/PyDictionary.java trunk/jython/src/org/python/core/PyEnumerate.java trunk/jython/src/org/python/core/PyFile.java trunk/jython/src/org/python/core/PyFloat.java trunk/jython/src/org/python/core/PyFunction.java trunk/jython/src/org/python/core/PyInteger.java trunk/jython/src/org/python/core/PyList.java trunk/jython/src/org/python/core/PyLong.java trunk/jython/src/org/python/core/PyMethod.java trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/core/PyProperty.java trunk/jython/src/org/python/core/PySlice.java trunk/jython/src/org/python/core/PyStaticMethod.java trunk/jython/src/org/python/core/PyString.java trunk/jython/src/org/python/core/PySuper.java trunk/jython/src/org/python/core/PyTuple.java trunk/jython/src/org/python/core/PyType.java trunk/jython/src/org/python/core/PyUnicode.java trunk/jython/src/org/python/core/PyXRange.java Modified: trunk/jython/Lib/test/test_descr.py =================================================================== --- trunk/jython/Lib/test/test_descr.py 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/Lib/test/test_descr.py 2009-10-14 06:02:01 UTC (rev 6856) @@ -4396,9 +4396,6 @@ # takes 1 arg) specials, - # Jython file lacks doc strings - descrdoc, - # New style classes don't support __del__: # http://bugs.jython.org/issue1057 delhook, Modified: trunk/jython/Misc/make_pydocs.py =================================================================== --- trunk/jython/Misc/make_pydocs.py 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/Misc/make_pydocs.py 2009-10-14 06:02:01 UTC (rev 6856) @@ -2,15 +2,21 @@ import __builtin__ def print_doc(out, obj, meth): - doc = (getattr(obj, meth)).__doc__ - if doc == None: + if meth == '__doc__': + doc = getattr(obj, meth) + bdname = '%s_doc' % obj.__name__ + else: + doc = getattr(obj, meth).__doc__ + bdname = '%s_%s_doc' % (obj.__name__, meth) + + if doc is None: doc = "" lines = doc.split("\n") - outstring = '\\n" + \n "'.join(lines) - print >> out, (' public final static String %s_%s_doc = ' - % (obj.__name__, meth)) + outstring = '\\n" + \n "'.join(format(line) for line in lines) + print >> out, (' public final static String %s = ' % bdname) print >> outfile, ' "%s";\n' % outstring +format = lambda line: line.replace('\\', '\\\\').replace('"', r'\"') opt = lambda n: getattr(__builtin__, n, None) def f(): pass @@ -58,13 +64,13 @@ ] outfile = open("BuiltinDocs.java", "w") -print >> outfile, '//generated by make_pydocs.py\n' +print >> outfile, '// generated by make_pydocs.py\n' print >> outfile, 'package org.python.core;\n' print >> outfile, 'public class BuiltinDocs {\n' for obj in types_list: - print >> outfile, ' //Docs for %s' % obj + print >> outfile, ' // Docs for %s' % obj for meth in dir(obj): print_doc(outfile, obj, meth) Modified: trunk/jython/src/org/python/core/BuiltinDocs.java =================================================================== --- trunk/jython/src/org/python/core/BuiltinDocs.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/BuiltinDocs.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -1,10 +1,10 @@ -//generated by make_pydocs.py +// generated by make_pydocs.py package org.python.core; public class BuiltinDocs { - //Docs for <type 'object'> + // Docs for <type 'object'> public final static String object___class___doc = "type(object) -> the object's type\n" + "type(name, bases, dict) -> a new type"; @@ -12,11 +12,8 @@ public final static String object___delattr___doc = "x.__delattr__('name') <==> del x.name"; - public final static String object___doc___doc = - "str(object) -> string\n" + - "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + public final static String object_doc = + "The most base type"; public final static String object___getattribute___doc = "x.__getattribute__('name') <==> x.name"; @@ -45,7 +42,7 @@ public final static String object___str___doc = "x.__str__() <==> str(x)"; - //Docs for <type 'type'> + // Docs for <type 'type'> public final static String type___base___doc = "The most base type"; @@ -91,11 +88,9 @@ "non-string. If the argument is outside the integer range a long object\n" + "will be returned instead."; - public final static String type___doc___doc = - "str(object) -> string\n" + - "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + public final static String type_doc = + "type(object) -> the object's type\n" + + "type(name, bases, dict) -> a new type"; public final static String type___flags___doc = "int(x[, base]) -> integer\n" + @@ -179,7 +174,7 @@ "mro() -> list\n" + "return a type's method resolution order"; - //Docs for <type 'unicode'> + // Docs for <type 'unicode'> public final static String unicode___add___doc = "x.__add__(y) <==> x+y"; @@ -193,11 +188,12 @@ public final static String unicode___delattr___doc = "x.__delattr__('name') <==> del x.name"; - public final static String unicode___doc___doc = - "str(object) -> string\n" + + public final static String unicode_doc = + "unicode(string [, encoding[, errors]]) -> object\n" + "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + "Create a new Unicode object from the given encoded string.\n" + + "encoding defaults to the current default string encoding.\n" + + "errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'."; public final static String unicode___eq___doc = "x.__eq__(y) <==> x==y"; @@ -327,7 +323,7 @@ "S.find(sub [,start [,end]]) -> int\n" + "\n" + "Return the lowest index in S where substring sub is found,\n" + - "such that sub is contained within s[start:end]. Optional\n" + + "such that sub is contained within s[start,end]. Optional\n" + "arguments start and end are interpreted as in slice notation.\n" + "\n" + "Return -1 on failure."; @@ -435,7 +431,7 @@ "S.rfind(sub [,start [,end]]) -> int\n" + "\n" + "Return the highest index in S where substring sub is found,\n" + - "such that sub is contained within s[start:end]. Optional\n" + + "such that sub is contained within s[start,end]. Optional\n" + "arguments start and end are interpreted as in slice notation.\n" + "\n" + "Return -1 on failure."; @@ -537,7 +533,7 @@ "Pad a numeric string x with zeros on the left, to fill a field\n" + "of the specified width. The string x is never truncated."; - //Docs for <type 'dict'> + // Docs for <type 'dict'> public final static String dict___class___doc = "type(object) -> the object's type\n" + "type(name, bases, dict) -> a new type"; @@ -554,11 +550,16 @@ public final static String dict___delitem___doc = "x.__delitem__(y) <==> del x[y]"; - public final static String dict___doc___doc = - "str(object) -> string\n" + - "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + public final static String dict_doc = + "dict() -> new empty dictionary.\n" + + "dict(mapping) -> new dictionary initialized from a mapping object's\n" + + " (key, value) pairs.\n" + + "dict(seq) -> new dictionary initialized as if via:\n" + + " d = {}\n" + + " for k, v in seq:\n" + + " d[k] = v\n" + + "dict(**kwargs) -> new dictionary initialized with the name=value pairs\n" + + " in the keyword argument list. For example: dict(one=1, two=2)"; public final static String dict___eq___doc = "x.__eq__(y) <==> x==y"; @@ -666,7 +667,7 @@ public final static String dict_values_doc = "D.values() -> list of D's values"; - //Docs for <type 'list'> + // Docs for <type 'list'> public final static String list___add___doc = "x.__add__(y) <==> x+y"; @@ -688,11 +689,9 @@ " \n" + " Use of negative indices is not supported."; - public final static String list___doc___doc = - "str(object) -> string\n" + - "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + public final static String list_doc = + "list() -> new list\n" + + "list(sequence) -> new list initialized from sequence's items"; public final static String list___eq___doc = "x.__eq__(y) <==> x==y"; @@ -804,7 +803,7 @@ "L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n" + "cmp(x, y) -> -1, 0, 1"; - //Docs for <type 'slice'> + // Docs for <type 'slice'> public final static String slice___class___doc = "type(object) -> the object's type\n" + "type(name, bases, dict) -> a new type"; @@ -815,11 +814,10 @@ public final static String slice___delattr___doc = "x.__delattr__('name') <==> del x.name"; - public final static String slice___doc___doc = - "str(object) -> string\n" + + public final static String slice_doc = + "slice([start,] stop[, step])\n" + "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + "Create a slice object. This is used for extended slicing (e.g. a[0:10:2])."; public final static String slice___getattribute___doc = "x.__getattribute__('name') <==> x.name"; @@ -865,7 +863,7 @@ public final static String slice_stop_doc = ""; - //Docs for <type 'super'> + // Docs for <type 'super'> public final static String super___class___doc = "type(object) -> the object's type\n" + "type(name, bases, dict) -> a new type"; @@ -873,11 +871,14 @@ public final static String super___delattr___doc = "x.__delattr__('name') <==> del x.name"; - public final static String super___doc___doc = - "str(object) -> string\n" + - "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + public final static String super_doc = + "super(type) -> unbound super object\n" + + "super(type, obj) -> bound super object; requires isinstance(obj, type)\n" + + "super(type, type2) -> bound super object; requires issubclass(type2, type)\n" + + "Typical use to call a cooperative superclass method:\n" + + "class C(B):\n" + + " def meth(self, arg):\n" + + " super(C, self).meth(arg)"; public final static String super___get___doc = "descr.__get__(obj[, type]) -> value"; @@ -918,7 +919,7 @@ public final static String super___thisclass___doc = "the class invoking super()"; - //Docs for <type 'staticmethod'> + // Docs for <type 'staticmethod'> public final static String staticmethod___class___doc = "type(object) -> the object's type\n" + "type(name, bases, dict) -> a new type"; @@ -926,11 +927,23 @@ public final static String staticmethod___delattr___doc = "x.__delattr__('name') <==> del x.name"; - public final static String staticmethod___doc___doc = - "str(object) -> string\n" + + public final static String staticmethod_doc = + "staticmethod(function) -> method\n" + "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + "Convert a function to be a static method.\n" + + "\n" + + "A static method does not receive an implicit first argument.\n" + + "To declare a static method, use this idiom:\n" + + "\n" + + " class C:\n" + + " def f(arg1, arg2, ...): ...\n" + + " f = staticmethod(f)\n" + + "\n" + + "It can be called either on the class (e.g. C.f()) or on an instance\n" + + "(e.g. C().f()). The instance is ignored except for its class.\n" + + "\n" + + "Static methods in Python are similar to those found in Java or C++.\n" + + "For a more advanced concept, see the classmethod builtin."; public final static String staticmethod___get___doc = "descr.__get__(obj[, type]) -> value"; @@ -962,7 +975,7 @@ public final static String staticmethod___str___doc = "x.__str__() <==> str(x)"; - //Docs for <type 'float'> + // Docs for <type 'float'> public final static String float___abs___doc = "x.__abs__() <==> abs(x)"; @@ -985,11 +998,10 @@ public final static String float___divmod___doc = "x.__divmod__(y) <==> divmod(x, y)"; - public final static String float___doc___doc = - "str(object) -> string\n" + + public final static String float_doc = + "float(x) -> floating point number\n" + "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + "Convert a string or number to a floating point number, if possible."; public final static String float___eq___doc = "x.__eq__(y) <==> x==y"; @@ -1125,7 +1137,7 @@ public final static String float___truediv___doc = "x.__truediv__(y) <==> x/y"; - //Docs for <type 'enumerate'> + // Docs for <type 'enumerate'> public final static String enumerate___class___doc = "type(object) -> the object's type\n" + "type(name, bases, dict) -> a new type"; @@ -1133,11 +1145,13 @@ public final static String enumerate___delattr___doc = "x.__delattr__('name') <==> del x.name"; - public final static String enumerate___doc___doc = - "str(object) -> string\n" + + public final static String enumerate_doc = + "enumerate(iterable) -> iterator for index, value of iterable\n" + "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + "Return an enumerate object. iterable must be an other object that supports\n" + + "iteration. The enumerate object yields pairs containing a count (from\n" + + "zero) and a value yielded by the iterable argument. enumerate is useful\n" + + "for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ..."; public final static String enumerate___getattribute___doc = "x.__getattribute__('name') <==> x.name"; @@ -1172,7 +1186,7 @@ public final static String enumerate_next_doc = "x.next() -> the next value, or raise StopIteration"; - //Docs for <type 'basestring'> + // Docs for <type 'basestring'> public final static String basestring___class___doc = "type(object) -> the object's type\n" + "type(name, bases, dict) -> a new type"; @@ -1180,11 +1194,8 @@ public final static String basestring___delattr___doc = "x.__delattr__('name') <==> del x.name"; - public final static String basestring___doc___doc = - "str(object) -> string\n" + - "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + public final static String basestring_doc = + "Type basestring cannot be instantiated; it is the base for str and unicode."; public final static String basestring___getattribute___doc = "x.__getattribute__('name') <==> x.name"; @@ -1213,7 +1224,7 @@ public final static String basestring___str___doc = "x.__str__() <==> str(x)"; - //Docs for <type 'long'> + // Docs for <type 'long'> public final static String long___abs___doc = "x.__abs__() <==> abs(x)"; @@ -1242,11 +1253,14 @@ public final static String long___divmod___doc = "x.__divmod__(y) <==> divmod(x, y)"; - public final static String long___doc___doc = - "str(object) -> string\n" + + public final static String long_doc = + "long(x[, base]) -> integer\n" + "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + "Convert a string or number to a long integer, if possible. A floating\n" + + "point argument will be truncated towards zero (this does not include a\n" + + "string representation of a floating point number!) When converting a\n" + + "string, use the optional base. It is an error to supply a base when\n" + + "converting a non-string."; public final static String long___float___doc = "x.__float__() <==> float(x)"; @@ -1380,7 +1394,7 @@ public final static String long___xor___doc = "x.__xor__(y) <==> x^y"; - //Docs for <type 'tuple'> + // Docs for <type 'tuple'> public final static String tuple___add___doc = "x.__add__(y) <==> x+y"; @@ -1394,11 +1408,11 @@ public final static String tuple___delattr___doc = "x.__delattr__('name') <==> del x.name"; - public final static String tuple___doc___doc = - "str(object) -> string\n" + + public final static String tuple_doc = + "tuple() -> an empty tuple\n" + + "tuple(sequence) -> tuple initialized from sequence's items\n" + "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + "If the argument is a tuple, the return value is the same object."; public final static String tuple___eq___doc = "x.__eq__(y) <==> x==y"; @@ -1468,7 +1482,7 @@ public final static String tuple___str___doc = "x.__str__() <==> str(x)"; - //Docs for <type 'str'> + // Docs for <type 'str'> public final static String str___add___doc = "x.__add__(y) <==> x+y"; @@ -1482,7 +1496,7 @@ public final static String str___delattr___doc = "x.__delattr__('name') <==> del x.name"; - public final static String str___doc___doc = + public final static String str_doc = "str(object) -> string\n" + "\n" + "Return a nice string representation of the object.\n" + @@ -1616,7 +1630,7 @@ "S.find(sub [,start [,end]]) -> int\n" + "\n" + "Return the lowest index in S where substring sub is found,\n" + - "such that sub is contained within s[start:end]. Optional\n" + + "such that sub is contained within s[start,end]. Optional\n" + "arguments start and end are interpreted as in slice notation.\n" + "\n" + "Return -1 on failure."; @@ -1712,7 +1726,7 @@ "S.rfind(sub [,start [,end]]) -> int\n" + "\n" + "Return the highest index in S where substring sub is found,\n" + - "such that sub is contained within s[start:end]. Optional\n" + + "such that sub is contained within s[start,end]. Optional\n" + "arguments start and end are interpreted as in slice notation.\n" + "\n" + "Return -1 on failure."; @@ -1813,7 +1827,7 @@ "Pad a numeric string S with zeros on the left, to fill a field\n" + "of the specified width. The string S is never truncated."; - //Docs for <type 'property'> + // Docs for <type 'property'> public final static String property___class___doc = "type(object) -> the object's type\n" + "type(name, bases, dict) -> a new type"; @@ -1824,11 +1838,17 @@ public final static String property___delete___doc = "descr.__delete__(obj)"; - public final static String property___doc___doc = - "str(object) -> string\n" + + public final static String property_doc = + "property(fget=None, fset=None, fdel=None, doc=None) -> property attribute\n" + "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + "fget is a function to be used for getting an attribute value, and likewise\n" + + "fset is a function for setting, and fdel a function for del'ing, an\n" + + "attribute. Typical use is to define a managed attribute x:\n" + + "class C(object):\n" + + " def getx(self): return self.__x\n" + + " def setx(self, value): self.__x = value\n" + + " def delx(self): del self.__x\n" + + " x = property(getx, setx, delx, \"I'm the 'x' property.\")"; public final static String property___get___doc = "descr.__get__(obj[, type]) -> value"; @@ -1872,7 +1892,7 @@ public final static String property_fset_doc = ""; - //Docs for <type 'int'> + // Docs for <type 'int'> public final static String int___abs___doc = "x.__abs__() <==> abs(x)"; @@ -1901,11 +1921,15 @@ public final static String int___divmod___doc = "x.__divmod__(y) <==> divmod(x, y)"; - public final static String int___doc___doc = - "str(object) -> string\n" + + public final static String int_doc = + "int(x[, base]) -> integer\n" + "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + "Convert a string or number to an integer, if possible. A floating point\n" + + "argument will be truncated towards zero (this does not include a string\n" + + "representation of a floating point number!) When converting a string, use\n" + + "the optional base. It is an error to supply a base when converting a\n" + + "non-string. If the argument is outside the integer range a long object\n" + + "will be returned instead."; public final static String int___float___doc = "x.__float__() <==> float(x)"; @@ -2039,7 +2063,7 @@ public final static String int___xor___doc = "x.__xor__(y) <==> x^y"; - //Docs for <type 'xrange'> + // Docs for <type 'xrange'> public final static String xrange___class___doc = "type(object) -> the object's type\n" + "type(name, bases, dict) -> a new type"; @@ -2047,11 +2071,12 @@ public final static String xrange___delattr___doc = "x.__delattr__('name') <==> del x.name"; - public final static String xrange___doc___doc = - "str(object) -> string\n" + + public final static String xrange_doc = + "xrange([start,] stop[, step]) -> xrange object\n" + "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + "Like range(), but instead of returning a list, returns an object that\n" + + "generates the numbers in the range on demand. For looping, this is \n" + + "slightly faster than range() and more memory efficient."; public final static String xrange___getattribute___doc = "x.__getattribute__('name') <==> x.name"; @@ -2092,7 +2117,7 @@ public final static String xrange___str___doc = "x.__str__() <==> str(x)"; - //Docs for <type 'file'> + // Docs for <type 'file'> public final static String file___class___doc = "type(object) -> the object's type\n" + "type(name, bases, dict) -> a new type"; @@ -2100,11 +2125,24 @@ public final static String file___delattr___doc = "x.__delattr__('name') <==> del x.name"; - public final static String file___doc___doc = - "str(object) -> string\n" + + public final static String file_doc = + "file(name[, mode[, buffering]]) -> file object\n" + "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + "Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n" + + "writing or appending. The file will be created if it doesn't exist\n" + + "when opened for writing or appending; it will be truncated when\n" + + "opened for writing. Add a 'b' to the mode for binary files.\n" + + "Add a '+' to the mode to allow simultaneous reading and writing.\n" + + "If the buffering argument is given, 0 means unbuffered, 1 means line\n" + + "buffered, and larger numbers specify the buffer size.\n" + + "Add a 'U' to mode to open the file for input with universal newline\n" + + "support. Any line ending in the input file will be seen as a '\\n'\n" + + "in Python. Also, a file so opened gains the attribute 'newlines';\n" + + "the value for this attribute is one of None (no newline read yet),\n" + + "'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n" + + "\n" + + "'U' cannot be combined with 'w' or '+' mode.\n" + + ""; public final static String file___enter___doc = "__enter__() -> self."; @@ -2244,7 +2282,7 @@ "For backward compatibility. File objects now include the performance\n" + "optimizations previously implemented in the xreadlines module."; - //Docs for <type 'complex'> + // Docs for <type 'complex'> public final static String complex___abs___doc = "x.__abs__() <==> abs(x)"; @@ -2267,11 +2305,11 @@ public final static String complex___divmod___doc = "x.__divmod__(y) <==> divmod(x, y)"; - public final static String complex___doc___doc = - "str(object) -> string\n" + + public final static String complex_doc = + "complex(real[, imag]) -> complex number\n" + "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + "Create a complex number from a real part and an optional imaginary part.\n" + + "This is equivalent to (real + imag*1j) where imag defaults to 0."; public final static String complex___eq___doc = "x.__eq__(y) <==> x==y"; @@ -2393,7 +2431,7 @@ public final static String complex_real_doc = "the real part of a complex number"; - //Docs for <type 'bool'> + // Docs for <type 'bool'> public final static String bool___abs___doc = "x.__abs__() <==> abs(x)"; @@ -2422,11 +2460,12 @@ public final static String bool___divmod___doc = "x.__divmod__(y) <==> divmod(x, y)"; - public final static String bool___doc___doc = - "str(object) -> string\n" + + public final static String bool_doc = + "bool(x) -> bool\n" + "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + "Returns True when the argument x is true, False otherwise.\n" + + "The builtins True and False are the only two instances of the class bool.\n" + + "The class bool is a subclass of the class int, and cannot be subclassed."; public final static String bool___float___doc = "x.__float__() <==> float(x)"; @@ -2560,7 +2599,7 @@ public final static String bool___xor___doc = "x.__xor__(y) <==> x^y"; - //Docs for <type 'classmethod'> + // Docs for <type 'classmethod'> public final static String classmethod___class___doc = "type(object) -> the object's type\n" + "type(name, bases, dict) -> a new type"; @@ -2568,11 +2607,26 @@ public final static String classmethod___delattr___doc = "x.__delattr__('name') <==> del x.name"; - public final static String classmethod___doc___doc = - "str(object) -> string\n" + + public final static String classmethod_doc = + "classmethod(function) -> method\n" + "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + "Convert a function to be a class method.\n" + + "\n" + + "A class method receives the class as implicit first argument,\n" + + "just like an instance method receives the instance.\n" + + "To declare a class method, use this idiom:\n" + + "\n" + + " class C:\n" + + " def f(cls, arg1, arg2, ...): ...\n" + + " f = classmethod(f)\n" + + "\n" + + "It can be called either on the class (e.g. C.f()) or on an instance\n" + + "(e.g. C().f()). The instance is ignored except for its class.\n" + + "If a class method is called for a derived class, the derived class\n" + + "object is passed as the implied first argument.\n" + + "\n" + + "Class methods are different than C++ or Java static methods.\n" + + "If you want those, see the staticmethod builtin."; public final static String classmethod___get___doc = "descr.__get__(obj[, type]) -> value"; @@ -2604,7 +2658,7 @@ public final static String classmethod___str___doc = "x.__str__() <==> str(x)"; - //Docs for <type 'function'> + // Docs for <type 'function'> public final static String function___call___doc = "x.__call__(...) <==> x(...)"; @@ -2618,11 +2672,13 @@ public final static String function___dict___doc = ""; - public final static String function___doc___doc = - "str(object) -> string\n" + + public final static String function_doc = + "function(code, globals[, name[, argdefs[, closure]]])\n" + "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + "Create a function object from a code object and a dictionary.\n" + + "The optional name string overrides the name from the code object.\n" + + "The optional argdefs tuple specifies the default argument values.\n" + + "The optional closure tuple supplies the bindings for free variables."; public final static String function___get___doc = "descr.__get__(obj[, type]) -> value"; @@ -2687,7 +2743,7 @@ public final static String function_func_name_doc = ""; - //Docs for <type 'instancemethod'> + // Docs for <type 'instancemethod'> public final static String instancemethod___call___doc = "x.__call__(...) <==> x(...)"; @@ -2701,11 +2757,10 @@ public final static String instancemethod___delattr___doc = "x.__delattr__('name') <==> del x.name"; - public final static String instancemethod___doc___doc = - "str(object) -> string\n" + + public final static String instancemethod_doc = + "instancemethod(function, instance, class)\n" + "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + "Create an instance method object."; public final static String instancemethod___get___doc = "descr.__get__(obj[, type]) -> value"; @@ -2746,7 +2801,7 @@ public final static String instancemethod_im_self_doc = "the instance to which a method is bound; None for unbound methods"; - //Docs for <type 'code'> + // Docs for <type 'code'> public final static String code___class___doc = "type(object) -> the object's type\n" + "type(name, bases, dict) -> a new type"; @@ -2757,11 +2812,11 @@ public final static String code___delattr___doc = "x.__delattr__('name') <==> del x.name"; - public final static String code___doc___doc = - "str(object) -> string\n" + + public final static String code_doc = + "code(argcount, nlocals, stacksize, flags, codestring, constants, names,\n" + + " varnames, filename, name, firstlineno, lnotab[, freevars[, cellvars]])\n" + "\n" + - "Return a nice string representation of the object.\n" + - "If the argument is a string, the return value is the same object."; + "Create a code object. Not for the faint of heart."; public final static String code___getattribute___doc = "x.__getattribute__('name') <==> x.name"; @@ -2832,7 +2887,7 @@ public final static String code_co_varnames_doc = ""; - //Docs for <type 'frame'> + // Docs for <type 'frame'> public final static String frame___class___doc = "type(object) -> the object's type\n" + "type(name, bases, dict) -> a new type"; @@ -2840,7 +2895,7 @@ public final static String frame___delattr___doc = "x.__delattr__('name') <==> del x.name"; - public final static String frame___doc___doc = + public final static String frame_doc = ""; public final static String frame___getattribute___doc = @@ -2906,7 +2961,7 @@ public final static String frame_f_trace_doc = ""; - //Docs for <type 'traceback'> + // Docs for <type 'traceback'> public final static String traceback___class___doc = "type(object) -> the object's type\n" + "type(name, bases, dict) -> a new type"; @@ -2914,7 +2969,7 @@ public final static String traceback___delattr___doc = "x.__delattr__('name') <==> del x.name"; - public final static String traceback___doc___doc = + public final static String traceback_doc = ""; public final static String traceback___getattribute___doc = Modified: trunk/jython/src/org/python/core/PyBaseString.java =================================================================== --- trunk/jython/src/org/python/core/PyBaseString.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PyBaseString.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -5,7 +5,7 @@ /** * base class for jython strings. */ -@ExposedType(name = "basestring", base = PyObject.class) +@ExposedType(name = "basestring", base = PyObject.class, doc = BuiltinDocs.basestring_doc) public abstract class PyBaseString extends PySequence { public static final PyType TYPE = PyType.fromClass(PyBaseString.class); Modified: trunk/jython/src/org/python/core/PyBoolean.java =================================================================== --- trunk/jython/src/org/python/core/PyBoolean.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PyBoolean.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -8,7 +8,7 @@ /** * A builtin python bool. */ -@ExposedType(name = "bool", isBaseType = false) +@ExposedType(name = "bool", isBaseType = false, doc = BuiltinDocs.bool_doc) public class PyBoolean extends PyInteger { public static final PyType TYPE = PyType.fromClass(PyBoolean.class); Modified: trunk/jython/src/org/python/core/PyClassMethod.java =================================================================== --- trunk/jython/src/org/python/core/PyClassMethod.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PyClassMethod.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -7,7 +7,7 @@ /** * The classmethod descriptor. */ -@ExposedType(name = "classmethod") +@ExposedType(name = "classmethod", doc = BuiltinDocs.classmethod_doc) public class PyClassMethod extends PyObject { public static final PyType TYPE = PyType.fromClass(PyClassMethod.class); Modified: trunk/jython/src/org/python/core/PyComplex.java =================================================================== --- trunk/jython/src/org/python/core/PyComplex.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PyComplex.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -10,14 +10,17 @@ /** * A builtin python complex number */ -@ExposedType(name = "complex") +@ExposedType(name = "complex", doc = BuiltinDocs.complex_doc) public class PyComplex extends PyObject { public static final PyType TYPE = PyType.fromClass(PyComplex.class); - @ExposedGet - public double real, imag; + @ExposedGet(doc = BuiltinDocs.complex_real_doc) + public double real; + @ExposedGet(doc = BuiltinDocs.complex_imag_doc) + public double imag; + static PyComplex J = new PyComplex(0, 1.); @ExposedNew Modified: trunk/jython/src/org/python/core/PyDictionary.java =================================================================== --- trunk/jython/src/org/python/core/PyDictionary.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PyDictionary.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -22,7 +22,7 @@ /** * A builtin python dictionary. */ -@ExposedType(name = "dict") +@ExposedType(name = "dict", doc = BuiltinDocs.dict_doc) public class PyDictionary extends PyObject implements ConcurrentMap { public static final PyType TYPE = PyType.fromClass(PyDictionary.class); Modified: trunk/jython/src/org/python/core/PyEnumerate.java =================================================================== --- trunk/jython/src/org/python/core/PyEnumerate.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PyEnumerate.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -8,7 +8,7 @@ /** * The Python builtin enumerate type. */ -@ExposedType(name = "enumerate", base = PyObject.class) +@ExposedType(name = "enumerate", base = PyObject.class, doc = BuiltinDocs.enumerate_doc) public class PyEnumerate extends PyIterator { public static final PyType TYPE = PyType.fromClass(PyEnumerate.class); Modified: trunk/jython/src/org/python/core/PyFile.java =================================================================== --- trunk/jython/src/org/python/core/PyFile.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PyFile.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -32,20 +32,20 @@ /** * The Python file type. Wraps an {@link TextIOBase} object. */ -@ExposedType(name = "file") +@ExposedType(name = "file", doc = BuiltinDocs.file_doc) public class PyFile extends PyObject { public static final PyType TYPE = PyType.fromClass(PyFile.class); /** The filename */ - @ExposedGet + @ExposedGet(doc = BuiltinDocs.file_name_doc) public PyObject name; /** The mode string */ - @ExposedGet + @ExposedGet(doc = BuiltinDocs.file_mode_doc) public String mode; - @ExposedGet + @ExposedGet(doc = BuiltinDocs.file_encoding_doc) public String encoding; /** Indicator dictating whether a space should be written to this @@ -525,17 +525,17 @@ file.checkClosed(); } - @ExposedGet(name = "closed") + @ExposedGet(name = "closed", doc = BuiltinDocs.file_closed_doc) public boolean getClosed() { return file.closed(); } - @ExposedGet(name = "newlines") + @ExposedGet(name = "newlines", doc = BuiltinDocs.file_newlines_doc) public PyObject getNewlines() { return file.getNewlines(); } - @ExposedGet(name = "softspace") + @ExposedGet(name = "softspace", doc = BuiltinDocs.file_softspace_doc) public PyObject getSoftspace() { // NOTE: not actual bools because CPython is this way return softspace ? Py.One : Py.Zero; Modified: trunk/jython/src/org/python/core/PyFloat.java =================================================================== --- trunk/jython/src/org/python/core/PyFloat.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PyFloat.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -13,7 +13,7 @@ /** * A builtin python float. */ -@ExposedType(name = "float") +@ExposedType(name = "float", doc = BuiltinDocs.float_doc) public class PyFloat extends PyObject { /** Precisions used by repr() and str(), respectively. */ Modified: trunk/jython/src/org/python/core/PyFunction.java =================================================================== --- trunk/jython/src/org/python/core/PyFunction.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PyFunction.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -11,7 +11,7 @@ /** * A Python function. */ -@ExposedType(name = "function", isBaseType = false) +@ExposedType(name = "function", isBaseType = false, doc = BuiltinDocs.function_doc) public class PyFunction extends PyObject { public static final PyType TYPE = PyType.fromClass(PyFunction.class); Modified: trunk/jython/src/org/python/core/PyInteger.java =================================================================== --- trunk/jython/src/org/python/core/PyInteger.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PyInteger.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -12,7 +12,7 @@ /** * A builtin python int. */ -@ExposedType(name = "int") +@ExposedType(name = "int", doc = BuiltinDocs.int_doc) public class PyInteger extends PyObject { public static final PyType TYPE = PyType.fromClass(PyInteger.class); Modified: trunk/jython/src/org/python/core/PyList.java =================================================================== --- trunk/jython/src/org/python/core/PyList.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PyList.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -19,7 +19,7 @@ import java.lang.reflect.Array; -@ExposedType(name = "list", base = PyObject.class) +@ExposedType(name = "list", base = PyObject.class, doc = BuiltinDocs.list_doc) public class PyList extends PySequenceList implements List { public static final PyType TYPE = PyType.fromClass(PyList.class); Modified: trunk/jython/src/org/python/core/PyLong.java =================================================================== --- trunk/jython/src/org/python/core/PyLong.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PyLong.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -14,7 +14,7 @@ * A builtin python long. This is implemented as a * java.math.BigInteger. */ -@ExposedType(name = "long") +@ExposedType(name = "long", doc = BuiltinDocs.long_doc) public class PyLong extends PyObject { public static final PyType TYPE = PyType.fromClass(PyLong.class); Modified: trunk/jython/src/org/python/core/PyMethod.java =================================================================== --- trunk/jython/src/org/python/core/PyMethod.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PyMethod.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -10,21 +10,21 @@ /** * A Python method. */ -@ExposedType(name = "instancemethod", isBaseType = false) +@ExposedType(name = "instancemethod", isBaseType = false, doc = BuiltinDocs.instancemethod_doc) public class PyMethod extends PyObject { public static final PyType TYPE = PyType.fromClass(PyMethod.class); /** The class associated with a method. */ - @ExposedGet + @ExposedGet(doc = BuiltinDocs.instancemethod_im_class_doc) public PyObject im_class; /** The function (or other callable) implementing a method. */ - @ExposedGet + @ExposedGet(doc = BuiltinDocs.instancemethod_im_func_doc) public PyObject im_func; /** The instance to which a method is bound; None for unbound methods. */ - @ExposedGet + @ExposedGet(doc = BuiltinDocs.instancemethod_im_self_doc) public PyObject im_self; public PyMethod(PyObject function, PyObject self, PyObject type) { Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PyObject.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -20,7 +20,7 @@ * All objects known to the Jython runtime system are represented by an instance * of the class <code>PyObject</code> or one of its subclasses. */ -@ExposedType(name = "object") +@ExposedType(name = "object", doc = BuiltinDocs.object_doc) public class PyObject implements Serializable { public static final PyType TYPE = PyType.fromClass(PyObject.class); Modified: trunk/jython/src/org/python/core/PyProperty.java =================================================================== --- trunk/jython/src/org/python/core/PyProperty.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PyProperty.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -3,21 +3,20 @@ import org.python.expose.ExposedGet; import org.python.expose.ExposedMethod; import org.python.expose.ExposedNew; -import org.python.expose.ExposedSet; import org.python.expose.ExposedType; -@ExposedType(name = "property") +@ExposedType(name = "property", doc = BuiltinDocs.property_doc) public class PyProperty extends PyObject { public static final PyType TYPE = PyType.fromClass(PyProperty.class); - @ExposedGet + @ExposedGet(doc = BuiltinDocs.property_fget_doc) protected PyObject fget; - @ExposedGet + @ExposedGet(doc = BuiltinDocs.property_fset_doc) protected PyObject fset; - @ExposedGet + @ExposedGet(doc = BuiltinDocs.property_fdel_doc) protected PyObject fdel; @ExposedGet(name = "__doc__") Modified: trunk/jython/src/org/python/core/PySlice.java =================================================================== --- trunk/jython/src/org/python/core/PySlice.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PySlice.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -9,18 +9,18 @@ /** * The Python slice object. */ -@ExposedType(name = "slice", isBaseType = false) +@ExposedType(name = "slice", isBaseType = false, doc = BuiltinDocs.slice_doc) public class PySlice extends PyObject { public static final PyType TYPE = PyType.fromClass(PySlice.class); - @ExposedGet + @ExposedGet(doc = BuiltinDocs.slice_start_doc) public PyObject start = Py.None; - @ExposedGet + @ExposedGet(doc = BuiltinDocs.slice_stop_doc) public PyObject stop = Py.None; - @ExposedGet + @ExposedGet(doc = BuiltinDocs.slice_step_doc) public PyObject step = Py.None; public PySlice() { Modified: trunk/jython/src/org/python/core/PyStaticMethod.java =================================================================== --- trunk/jython/src/org/python/core/PyStaticMethod.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PyStaticMethod.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -7,7 +7,7 @@ /** * The staticmethod descriptor. */ -@ExposedType(name = "staticmethod") +@ExposedType(name = "staticmethod", doc = BuiltinDocs.staticmethod_doc) public class PyStaticMethod extends PyObject { public static final PyType TYPE = PyType.fromClass(PyStaticMethod.class); Modified: trunk/jython/src/org/python/core/PyString.java =================================================================== --- trunk/jython/src/org/python/core/PyString.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PyString.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -13,7 +13,7 @@ /** * A builtin python string. */ -@ExposedType(name = "str") +@ExposedType(name = "str", doc = BuiltinDocs.str_doc) public class PyString extends PyBaseString { public static final PyType TYPE = PyType.fromClass(PyString.class); Modified: trunk/jython/src/org/python/core/PySuper.java =================================================================== --- trunk/jython/src/org/python/core/PySuper.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PySuper.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -9,18 +9,18 @@ /** * The Python super type. */ -@ExposedType(name = "super") +@ExposedType(name = "super", doc = BuiltinDocs.super_doc) public class PySuper extends PyObject { public static final PyType TYPE = PyType.fromClass(PySuper.class); - @ExposedGet(name = "__thisclass__") + @ExposedGet(name = "__thisclass__", doc = BuiltinDocs.super___thisclass___doc) protected PyType superType; - @ExposedGet(name = "__self__") + @ExposedGet(name = "__self__", doc = BuiltinDocs.super___self___doc) protected PyObject obj; - @ExposedGet(name = "__self_class__") + @ExposedGet(name = "__self_class__", doc = BuiltinDocs.super___self_class___doc) protected PyType objType; public PySuper() { Modified: trunk/jython/src/org/python/core/PyTuple.java =================================================================== --- trunk/jython/src/org/python/core/PyTuple.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PyTuple.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -17,7 +17,7 @@ /** * A builtin python tuple. */ -@ExposedType(name = "tuple", base = PyObject.class) +@ExposedType(name = "tuple", base = PyObject.class, doc = BuiltinDocs.tuple_doc) public class PyTuple extends PySequenceList implements List { public static final PyType TYPE = PyType.fromClass(PyTuple.class); Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PyType.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -25,7 +25,7 @@ /** * The Python Type object implementation. */ -@ExposedType(name = "type") +@ExposedType(name = "type", doc = BuiltinDocs.type_doc) public class PyType extends PyObject implements Serializable { public static PyType TYPE = fromClass(PyType.class); @@ -640,7 +640,6 @@ bases = cleanedBases.toArray(new PyObject[cleanedBases.size()]); } - //XXX: needs __doc__ @ExposedGet(name = "__base__") public PyObject getBase() { if (base == null) @@ -648,7 +647,6 @@ return base; } - //XXX: needs __doc__ @ExposedGet(name = "__bases__") public PyObject getBases() { return new PyTuple(bases); Modified: trunk/jython/src/org/python/core/PyUnicode.java =================================================================== --- trunk/jython/src/org/python/core/PyUnicode.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PyUnicode.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -17,7 +17,7 @@ /** * a builtin python unicode string. */ -@ExposedType(name = "unicode", base = PyBaseString.class) +@ExposedType(name = "unicode", base = PyBaseString.class, doc = BuiltinDocs.unicode_doc) public class PyUnicode extends PyString implements Iterable { private enum Plane { Modified: trunk/jython/src/org/python/core/PyXRange.java =================================================================== --- trunk/jython/src/org/python/core/PyXRange.java 2009-10-14 03:19:24 UTC (rev 6855) +++ trunk/jython/src/org/python/core/PyXRange.java 2009-10-14 06:02:01 UTC (rev 6856) @@ -8,7 +8,8 @@ /** * The builtin xrange type. */ -@ExposedType(name = "xrange", base = PyObject.class, isBaseType = false) +@ExposedType(name = "xrange", base = PyObject.class, isBaseType = false, + doc = BuiltinDocs.xrange_doc) public class PyXRange extends PySequence { public static final PyType TYPE = PyType.fromClass(PyXRange.class); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-14 03:19:45
|
Revision: 6855 http://jython.svn.sourceforge.net/jython/?rev=6855&view=rev Author: pjenvey Date: 2009-10-14 03:19:24 +0000 (Wed, 14 Oct 2009) Log Message: ----------- add support for specifying docstrings in ExposedType/ExposedGet annotations. exposed type.__doc__, which for the most part removes the need for PyObject.getDoc Modified Paths: -------------- trunk/jython/src/org/python/core/PyBuiltinCallable.java trunk/jython/src/org/python/core/PyDataDescr.java trunk/jython/src/org/python/core/PyFunction.java trunk/jython/src/org/python/core/PyMethod.java trunk/jython/src/org/python/core/PyMethodDescr.java trunk/jython/src/org/python/core/PyModule.java trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/core/PyReflectedFunction.java trunk/jython/src/org/python/core/PyType.java trunk/jython/src/org/python/expose/BaseTypeBuilder.java trunk/jython/src/org/python/expose/ExposedGet.java trunk/jython/src/org/python/expose/ExposedType.java trunk/jython/src/org/python/expose/TypeBuilder.java trunk/jython/src/org/python/expose/generate/DescriptorExposer.java trunk/jython/src/org/python/expose/generate/DescriptorVisitor.java trunk/jython/src/org/python/expose/generate/ExposedFieldFinder.java trunk/jython/src/org/python/expose/generate/ExposedMethodFinder.java trunk/jython/src/org/python/expose/generate/ExposedTypeProcessor.java trunk/jython/src/org/python/expose/generate/ExposedTypeVisitor.java trunk/jython/src/org/python/expose/generate/TypeExposer.java trunk/jython/tests/java/org/python/expose/generate/ExposeMethodFinderTest.java trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java trunk/jython/tests/java/org/python/expose/generate/ExposedTypeVisitorTest.java trunk/jython/tests/java/org/python/expose/generate/SimpleExposed.java trunk/jython/tests/java/org/python/expose/generate/TypeExposerTest.java Modified: trunk/jython/src/org/python/core/PyBuiltinCallable.java =================================================================== --- trunk/jython/src/org/python/core/PyBuiltinCallable.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/src/org/python/core/PyBuiltinCallable.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -30,7 +30,7 @@ } @ExposedGet(name = "__doc__") - public String fastGetDoc() { + public String getDoc() { return doc; } Modified: trunk/jython/src/org/python/core/PyDataDescr.java =================================================================== --- trunk/jython/src/org/python/core/PyDataDescr.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/src/org/python/core/PyDataDescr.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -17,6 +17,8 @@ protected Class ofType; + private String doc; + /** * @param onType - * the type the descriptor belongs to @@ -25,8 +27,8 @@ * @param ofType - * the type returned by the descriptor */ - public PyDataDescr(PyType onType, String name, Class ofType) { - this(name, ofType); + public PyDataDescr(PyType onType, String name, Class ofType, String doc) { + this(name, ofType, doc); setType(onType); } @@ -39,9 +41,10 @@ * @param ofType - * the type returned by the descriptor */ - public PyDataDescr(String name, Class ofType) { + public PyDataDescr(String name, Class ofType, String doc) { this.name = name; this.ofType = ofType; + this.doc = doc; } /** @@ -116,6 +119,11 @@ return String.format("<attribute '%s' of '%s' objects>", name, dtype.fastGetName()); } + @ExposedGet(name = "__doc__") + public String getDoc() { + return doc; + } + /** * Return the name this descriptor is exposed as. * Modified: trunk/jython/src/org/python/core/PyFunction.java =================================================================== --- trunk/jython/src/org/python/core/PyFunction.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/src/org/python/core/PyFunction.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -284,11 +284,6 @@ } @Override - public PyObject getDoc() { - return __doc__; - } - - @Override public PyObject __get__(PyObject obj, PyObject type) { return function___get__(obj, type); } Modified: trunk/jython/src/org/python/core/PyMethod.java =================================================================== --- trunk/jython/src/org/python/core/PyMethod.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/src/org/python/core/PyMethod.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -285,9 +285,9 @@ return hashCode ^ im_func.hashCode(); } - @Override + @ExposedGet(name = "__doc__") public PyObject getDoc() { - return im_func.getDoc(); + return im_func.__getattr__("__doc__"); } @Override Modified: trunk/jython/src/org/python/core/PyMethodDescr.java =================================================================== --- trunk/jython/src/org/python/core/PyMethodDescr.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/src/org/python/core/PyMethodDescr.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -21,8 +21,8 @@ } @ExposedGet(name = "__doc__") - public String fastGetDoc() { - return meth.fastGetDoc(); + public String getDoc() { + return meth.getDoc(); } public int getMaxargs() { Modified: trunk/jython/src/org/python/core/PyModule.java =================================================================== --- trunk/jython/src/org/python/core/PyModule.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/src/org/python/core/PyModule.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -80,18 +80,6 @@ throw Py.TypeError("readonly attribute"); } - @ExposedGet(name = "__doc__") - public PyObject getDoc() { - PyObject dict = fastGetDict(); - if (dict != null) { - PyObject doc = dict.__finditem__("__doc__"); - if (doc != null) { - return doc; - } - } - return moduleDoc; - } - protected PyObject impAttr(String name) { PyObject path = __dict__.__finditem__("__path__"); PyObject pyName = __dict__.__finditem__("__name__"); Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/src/org/python/core/PyObject.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -111,19 +111,6 @@ return objtype; } - //XXX: needs doc - @ExposedGet(name = "__doc__") - public PyObject getDoc() { - PyObject d = fastGetDict(); - if (d != null) { - PyObject doc = d.__finditem__("__doc__"); - if(doc != null) { - return doc; - } - } - return Py.None; - } - /** * Dispatch __init__ behavior */ Modified: trunk/jython/src/org/python/core/PyReflectedFunction.java =================================================================== --- trunk/jython/src/org/python/core/PyReflectedFunction.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/src/org/python/core/PyReflectedFunction.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -53,11 +53,6 @@ container, wherefound); } - @Override - public PyObject getDoc() { - return __doc__; - } - private ReflectedArgs makeArgs(Method m) { return new ReflectedArgs(m, m.getParameterTypes(), Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/src/org/python/core/PyType.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -292,7 +292,8 @@ * Create the __dict__ descriptor. */ private void createDictSlot() { - dict.__setitem__("__dict__", new PyDataDescr(this, "__dict__", PyObject.class) { + String doc = "dictionary for instance variables (if defined)"; + dict.__setitem__("__dict__", new PyDataDescr(this, "__dict__", PyObject.class, doc) { @Override public Object invokeGet(PyObject obj) { return obj.getDict(); @@ -325,7 +326,8 @@ * Create the __weakref__ descriptor. */ private void createWeakrefSlot() { - dict.__setitem__("__weakref__", new PyDataDescr(this, "__weakref__", PyObject.class) { + String doc = "list of weak references to the object (if defined)"; + dict.__setitem__("__weakref__", new PyDataDescr(this, "__weakref__", PyObject.class, doc) { private static final String writeMsg = "attribute '%s' of '%s' objects is not writable"; @@ -484,6 +486,21 @@ TypeBuilder builder = classToBuilder.get(underlying_class); name = builder.getName(); dict = builder.getDict(this); + String doc = builder.getDoc(); + // XXX: Can't create a __doc__ str until the PyBaseString/PyString types are + // created + if (dict.__finditem__("__doc__") == null && forClass != PyBaseString.class + && forClass != PyString.class) { + PyObject docObj; + if (doc != null) { + docObj = new PyString(doc); + } else { + // XXX: Hack: Py.None may be null during bootstrapping. Most types + // encountered then should have docstrings anyway + docObj = Py.None == null ? new PyString() : Py.None; + } + dict.__setitem__("__doc__", docObj); + } setIsBaseType(builder.getIsBaseType()); instantiable = dict.__finditem__("__new__") != null; fillHasSetAndDelete(); @@ -1543,14 +1560,15 @@ } /** - * Equivalent of CPython's typeobject type_get_doc; handles __doc__ descriptors. + * Equivalent of CPython's typeobject.c::type_get_doc; handles __doc__ descriptors. */ + @ExposedGet(name = "__doc__") public PyObject getDoc() { - PyObject doc = super.getDoc(); - if (!builtin && doc != null && doc.getType().lookup("__get__") != null) { - return doc.__get__(null, this); + PyObject doc = dict.__finditem__("__doc__"); + if (doc == null) { + return Py.None; } - return doc; + return doc.__get__(null, this); } boolean getUsesObjectGetattribute() { Modified: trunk/jython/src/org/python/expose/BaseTypeBuilder.java =================================================================== --- trunk/jython/src/org/python/expose/BaseTypeBuilder.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/src/org/python/expose/BaseTypeBuilder.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -24,16 +24,20 @@ private boolean isBaseType; + private String doc; + public BaseTypeBuilder(String name, Class<?> typeClass, Class<?> baseClass, boolean isBaseType, + String doc, PyBuiltinMethod[] meths, PyDataDescr[] descrs, PyNewWrapper newWrapper) { this.typeClass = typeClass; this.baseClass = baseClass; this.isBaseType = isBaseType; + this.doc = doc; this.name = name; this.descrs = descrs; this.meths = meths; @@ -72,4 +76,8 @@ public boolean getIsBaseType() { return isBaseType; } + + public String getDoc() { + return doc; + } } Modified: trunk/jython/src/org/python/expose/ExposedGet.java =================================================================== --- trunk/jython/src/org/python/expose/ExposedGet.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/src/org/python/expose/ExposedGet.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -10,4 +10,9 @@ public @interface ExposedGet { String name() default ""; + + /** + * Returns the __doc__ String for this descriptor. + */ + String doc() default ""; } Modified: trunk/jython/src/org/python/expose/ExposedType.java =================================================================== --- trunk/jython/src/org/python/expose/ExposedType.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/src/org/python/expose/ExposedType.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -31,4 +31,9 @@ * @return Whether this type allows subclassing. */ boolean isBaseType() default true; + + /** + * Returns the __doc__ String for this type. + */ + String doc() default ""; } Modified: trunk/jython/src/org/python/expose/TypeBuilder.java =================================================================== --- trunk/jython/src/org/python/expose/TypeBuilder.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/src/org/python/expose/TypeBuilder.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -17,4 +17,6 @@ public Class getBase(); public boolean getIsBaseType(); + + public String getDoc(); } Modified: trunk/jython/src/org/python/expose/generate/DescriptorExposer.java =================================================================== --- trunk/jython/src/org/python/expose/generate/DescriptorExposer.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/src/org/python/expose/generate/DescriptorExposer.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -15,6 +15,8 @@ private String name; + private String doc; + private String getterMethodName, getterFieldName, setterMethodName, setterFieldName, deleterMethodName; @@ -36,6 +38,10 @@ } public void addMethodGetter(String methodName, String desc) { + addMethodGetter(methodName, desc, null); + } + + public void addMethodGetter(String methodName, String desc, String doc) { if(hasGetter()) { error("Descriptor can only have one getter"); } @@ -44,14 +50,20 @@ } setOfType(Type.getReturnType(desc)); getterMethodName = methodName; + this.doc = doc; } public void addFieldGetter(String fieldName, Type fieldType) { + addFieldGetter(fieldName, fieldType, null); + } + + public void addFieldGetter(String fieldName, Type fieldType, String doc) { if(hasGetter()) { error("Can only have one getter for a descriptor"); } setOfType(fieldType); getterFieldName = fieldName; + this.doc = doc; } public boolean hasGetter() { @@ -130,7 +142,12 @@ } else { mv.visitLdcInsn(ofType); } - superConstructor(STRING, CLASS); + if (doc == null) { + mv.visitInsn(ACONST_NULL); + } else { + mv.visitLdcInsn(doc); + } + superConstructor(STRING, CLASS, STRING); endConstructor(); } Modified: trunk/jython/src/org/python/expose/generate/DescriptorVisitor.java =================================================================== --- trunk/jython/src/org/python/expose/generate/DescriptorVisitor.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/src/org/python/expose/generate/DescriptorVisitor.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -4,14 +4,18 @@ private String val; + private String doc; + DescriptorVisitor(String defaultName) { val = defaultName; } @Override public void visit(String name, Object value) { - if(name.equals("name")) { + if (name.equals("name")) { val = (String)value; + } else if (name.equals("doc")) { + doc = (String)value; } else { super.visit(name, value); } @@ -19,8 +23,8 @@ @Override public void visitEnd() { - handleResult(val); + handleResult(val, doc); } - public abstract void handleResult(String name); -} \ No newline at end of file + public abstract void handleResult(String name, String doc); +} Modified: trunk/jython/src/org/python/expose/generate/ExposedFieldFinder.java =================================================================== --- trunk/jython/src/org/python/expose/generate/ExposedFieldFinder.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/src/org/python/expose/generate/ExposedFieldFinder.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -10,6 +10,8 @@ private FieldVisitor delegate; + private String doc; + public ExposedFieldFinder(String name, FieldVisitor delegate) { fieldName = name; this.delegate = delegate; @@ -20,15 +22,15 @@ return new DescriptorVisitor(fieldName) { @Override - public void handleResult(String name) { - exposeAsGet(name); + public void handleResult(String name, String doc) { + exposeAsGet(name, doc); } }; } else if(EXPOSED_SET.getDescriptor().equals(desc)) { return new DescriptorVisitor(fieldName) { @Override - public void handleResult(String name) { + public void handleResult(String name, String doc) { exposeAsSet(name); } }; @@ -37,7 +39,7 @@ } } - public abstract void exposeAsGet(String name); + public abstract void exposeAsGet(String name, String doc); public abstract void exposeAsSet(String name); Modified: trunk/jython/src/org/python/expose/generate/ExposedMethodFinder.java =================================================================== --- trunk/jython/src/org/python/expose/generate/ExposedMethodFinder.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/src/org/python/expose/generate/ExposedMethodFinder.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -63,7 +63,7 @@ */ public abstract void handleNewExposer(Exposer exposer); - public abstract void exposeAsGetDescriptor(String descName); + public abstract void exposeAsGetDescriptor(String descName, String doc); public abstract void exposeAsSetDescriptor(String descName); @@ -93,15 +93,15 @@ return new DescriptorVisitor(methodName) { @Override - public void handleResult(String name) { - exposeAsGetDescriptor(name); + public void handleResult(String name, String doc) { + exposeAsGetDescriptor(name, doc); } }; } else if(desc.equals(EXPOSED_SET.getDescriptor())) { return new DescriptorVisitor(methodName) { @Override - public void handleResult(String name) { + public void handleResult(String name, String doc) { exposeAsSetDescriptor(name); } }; @@ -109,7 +109,7 @@ return new DescriptorVisitor(methodName) { @Override - public void handleResult(String name) { + public void handleResult(String name, String doc) { exposeAsDeleteDescriptor(name); } }; Modified: trunk/jython/src/org/python/expose/generate/ExposedTypeProcessor.java =================================================================== --- trunk/jython/src/org/python/expose/generate/ExposedTypeProcessor.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/src/org/python/expose/generate/ExposedTypeProcessor.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -111,6 +111,8 @@ private boolean isBaseType = true; + private String doc; + private boolean generatedStaticBlock; private TypeProcessor(ClassVisitor cv) { @@ -135,18 +137,13 @@ return new ExposedTypeVisitor(onType, visitor) { @Override - public void handleResult(String name) { - typeName = name; + public void handleResult(String typeName, Type baseType, boolean isBaseType, + String doc) { + ExposedTypeProcessor.this.typeName = typeName; + TypeProcessor.this.baseType = baseType; + TypeProcessor.this.isBaseType = isBaseType; + TypeProcessor.this.doc = doc; } - - @Override - public void handleResult(Type base) { - baseType = base; - } - - public void handleResult(boolean boolIsBaseType) { - isBaseType = boolIsBaseType; - } }; } return visitor; @@ -166,6 +163,7 @@ typeExposer = new TypeExposer(onType, baseType, isBaseType, + doc, getName(), methodExposers, descExposers.values(), @@ -266,8 +264,8 @@ } @Override - public void exposeAsGetDescriptor(String descName) { - getDescriptorExposer(descName).addMethodGetter(name, desc); + public void exposeAsGetDescriptor(String descName, String doc) { + getDescriptorExposer(descName).addMethodGetter(name, desc, doc); } @Override @@ -303,8 +301,8 @@ return new ExposedFieldFinder(fieldName, passthroughVisitor) { @Override - public void exposeAsGet(String name) { - getDescriptorExposer(name).addFieldGetter(fieldName, Type.getType(desc)); + public void exposeAsGet(String name, String doc) { + getDescriptorExposer(name).addFieldGetter(fieldName, Type.getType(desc), doc); } @Override Modified: trunk/jython/src/org/python/expose/generate/ExposedTypeVisitor.java =================================================================== --- trunk/jython/src/org/python/expose/generate/ExposedTypeVisitor.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/src/org/python/expose/generate/ExposedTypeVisitor.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -16,6 +16,8 @@ private boolean isBaseType = true; + private String doc; + private final AnnotationVisitor passthrough; public ExposedTypeVisitor(Type onType, AnnotationVisitor passthrough) { @@ -25,12 +27,14 @@ @Override public void visit(String name, Object value) { - if(name.equals("name")) { + if (name.equals("name")) { typeName = (String)value; - } else if(name.equals("base")) { + } else if (name.equals("base")) { base = (Type)value; - } else if(name.equals("isBaseType")) { + } else if (name.equals("isBaseType")) { isBaseType = (Boolean)value; + } else if (name.equals("doc")) { + doc = (String)value; } else { super.visit(name, value); } @@ -41,25 +45,21 @@ @Override public void visitEnd() { - if(typeName == null) { + if (typeName == null) { String name = onType.getClassName(); typeName = name.substring(name.lastIndexOf(".") + 1); } - handleResult(typeName); - handleResult(base); - handleResult(isBaseType); + handleResult(typeName, base, isBaseType, doc); if (passthrough != null) { passthrough.visitEnd(); } } - public abstract void handleResult(Type base); - - public abstract void handleResult(boolean isBaseType); - /** - * @param name - - * the name the type should be exposed as from the annotation. + * @param name the name the type should be exposed as from the annotation + * @param name the specified base type + * @param name the value of the isBaseType flag + * @param name the type's docstring */ - public abstract void handleResult(String name); + public abstract void handleResult(String name, Type base, boolean isBaseType, String doc); } Modified: trunk/jython/src/org/python/expose/generate/TypeExposer.java =================================================================== --- trunk/jython/src/org/python/expose/generate/TypeExposer.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/src/org/python/expose/generate/TypeExposer.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -20,6 +20,8 @@ private boolean isBaseType; + private String doc; + private Type onType; private String name; @@ -35,6 +37,7 @@ public TypeExposer(Type onType, Type baseType, boolean isBaseType, + String doc, String name, Collection<MethodExposer> methods, Collection<DescriptorExposer> descriptors, @@ -42,6 +45,7 @@ super(BaseTypeBuilder.class, makeGeneratedName(onType)); this.baseType = baseType; this.isBaseType = isBaseType; + this.doc = doc; this.onType = onType; this.name = name; this.methods = methods; @@ -106,6 +110,11 @@ mv.visitLdcInsn(onType); mv.visitLdcInsn(baseType); mv.visitLdcInsn(isBaseType); + if (doc == null) { + mv.visitInsn(ACONST_NULL); + } else { + mv.visitLdcInsn(doc); + } mv.visitLdcInsn(numNames); mv.visitTypeInsn(ANEWARRAY, BUILTIN_METHOD.getInternalName()); mv.visitVarInsn(ASTORE, 1); @@ -140,7 +149,7 @@ } else { mv.visitInsn(ACONST_NULL); } - superConstructor(STRING, CLASS, CLASS, BOOLEAN, ABUILTIN_METHOD, ADATA_DESCR, + superConstructor(STRING, CLASS, CLASS, BOOLEAN, STRING, ABUILTIN_METHOD, ADATA_DESCR, PYNEWWRAPPER); endConstructor(); } Modified: trunk/jython/tests/java/org/python/expose/generate/ExposeMethodFinderTest.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/ExposeMethodFinderTest.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/tests/java/org/python/expose/generate/ExposeMethodFinderTest.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -36,7 +36,7 @@ } @Override - public void exposeAsGetDescriptor(String descName) { + public void exposeAsGetDescriptor(String descName, String doc) { getName = descName; } Modified: trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -7,6 +7,7 @@ import org.python.core.PyBuiltinCallable; import org.python.core.PyDataDescr; import org.python.core.PyObject; +import org.python.core.PyString; import org.python.core.PyType; public class ExposedTypeProcessorTest extends InterpTestCase { @@ -42,6 +43,7 @@ desc.setType(simp.getType()); assertEquals(doctoredSimple.getField("toStringVal").get(simp), desc.__get__(simp, PyType.fromClass(doctoredSimple)).toString()); + assertEquals(desc.__getattr__("__doc__"), new PyString("tostring docs")); } public void testNoAnnotationType() throws IOException { Modified: trunk/jython/tests/java/org/python/expose/generate/ExposedTypeVisitorTest.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/ExposedTypeVisitorTest.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/tests/java/org/python/expose/generate/ExposedTypeVisitorTest.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -12,18 +12,11 @@ etv = new ExposedTypeVisitor(Type.getType("Lsimpletype;"), null) { @Override - public void handleResult(String name) { + public void handleResult(String name, Type base, boolean isBaseType, String doc) { result = name; - } - - @Override - public void handleResult(Type base) { baseResult = base; - } - - @Override - public void handleResult(boolean isBaseType) { isBaseTypeResult = isBaseType; + docResult = doc; } }; } @@ -38,10 +31,12 @@ etv.visit("name", "different"); etv.visit("base", Type.getType(PyObject.class)); etv.visit("isBaseType", false); + etv.visit("doc", "Different docstring"); etv.visitEnd(); assertEquals("different", result); assertEquals(Type.getType(PyObject.class), baseResult); assertEquals(false, isBaseTypeResult); + assertEquals("Different docstring", docResult); } ExposedTypeVisitor etv; @@ -51,4 +46,6 @@ private Type baseResult; private boolean isBaseTypeResult; + + private String docResult; } Modified: trunk/jython/tests/java/org/python/expose/generate/SimpleExposed.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/SimpleExposed.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/tests/java/org/python/expose/generate/SimpleExposed.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -4,7 +4,6 @@ import org.python.core.PyInteger; import org.python.core.PyNewWrapper; import org.python.core.PyObject; -import org.python.core.PyString; import org.python.core.PyType; import org.python.core.ThreadState; import org.python.expose.ExposedClassMethod; @@ -16,7 +15,7 @@ import org.python.expose.ExposedType; import org.python.expose.MethodType; -@ExposedType(name = "simpleexposed", isBaseType = false) +@ExposedType(name = "simpleexposed", isBaseType = false, doc = "Docstring") public class SimpleExposed extends PyObject { public void method() {} @@ -147,7 +146,7 @@ } } - @ExposedGet(name = "tostring") + @ExposedGet(name = "tostring", doc = "tostring docs") public String toStringVal = TO_STRING_RETURN; public static final String TO_STRING_RETURN = "A simple test class"; Modified: trunk/jython/tests/java/org/python/expose/generate/TypeExposerTest.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/TypeExposerTest.java 2009-10-13 02:31:45 UTC (rev 6854) +++ trunk/jython/tests/java/org/python/expose/generate/TypeExposerTest.java 2009-10-14 03:19:24 UTC (rev 6855) @@ -22,6 +22,7 @@ assertEquals(false, t.getIsBaseType()); PyType type = PyType.fromClass(SimpleExposed.class); PyObject dict = t.getDict(type); + assertEquals(dict.__finditem__("__doc__"), Py.newString("Docstring")); assertNotNull(dict.__finditem__("simple_method")); assertNotNull(dict.__finditem__("prefixed")); assertNotNull(dict.__finditem__("__str__")); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |