pywin32-checkins Mailing List for Python for Windows Extensions (Page 24)
OLD project page for the Python extensions for Windows
Brought to you by:
mhammond
You can subscribe to this list here.
2003 |
Jan
|
Feb
|
Mar
|
Apr
(2) |
May
(1) |
Jun
(6) |
Jul
(50) |
Aug
(11) |
Sep
(24) |
Oct
(184) |
Nov
(118) |
Dec
(22) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2004 |
Jan
(31) |
Feb
(25) |
Mar
(34) |
Apr
(105) |
May
(49) |
Jun
(38) |
Jul
(39) |
Aug
(7) |
Sep
(98) |
Oct
(79) |
Nov
(20) |
Dec
(17) |
2005 |
Jan
(66) |
Feb
(32) |
Mar
(43) |
Apr
(30) |
May
(58) |
Jun
(30) |
Jul
(16) |
Aug
(4) |
Sep
(21) |
Oct
(42) |
Nov
(11) |
Dec
(14) |
2006 |
Jan
(42) |
Feb
(30) |
Mar
(22) |
Apr
(1) |
May
(9) |
Jun
(15) |
Jul
(20) |
Aug
(9) |
Sep
(8) |
Oct
(1) |
Nov
(9) |
Dec
(43) |
2007 |
Jan
(52) |
Feb
(45) |
Mar
(20) |
Apr
(12) |
May
(59) |
Jun
(39) |
Jul
(35) |
Aug
(31) |
Sep
(17) |
Oct
(20) |
Nov
(4) |
Dec
(4) |
2008 |
Jan
(28) |
Feb
(111) |
Mar
(4) |
Apr
(27) |
May
(40) |
Jun
(27) |
Jul
(32) |
Aug
(94) |
Sep
(87) |
Oct
(153) |
Nov
(336) |
Dec
(331) |
2009 |
Jan
(298) |
Feb
(127) |
Mar
(20) |
Apr
(8) |
May
|
Jun
(10) |
Jul
(6) |
Aug
|
Sep
(2) |
Oct
(2) |
Nov
|
Dec
(1) |
2010 |
Jan
(7) |
Feb
(1) |
Mar
|
Apr
|
May
(15) |
Jun
(4) |
Jul
(3) |
Aug
(28) |
Sep
(1) |
Oct
(19) |
Nov
(16) |
Dec
(6) |
2011 |
Jan
(2) |
Feb
(18) |
Mar
(17) |
Apr
(12) |
May
(5) |
Jun
(11) |
Jul
(7) |
Aug
(2) |
Sep
(2) |
Oct
(4) |
Nov
(4) |
Dec
|
2012 |
Jan
(6) |
Feb
(2) |
Mar
|
Apr
(8) |
May
(4) |
Jun
(3) |
Jul
(13) |
Aug
(27) |
Sep
(8) |
Oct
(9) |
Nov
(3) |
Dec
(2) |
2013 |
Jan
|
Feb
(1) |
Mar
(5) |
Apr
(10) |
May
|
Jun
(2) |
Jul
|
Aug
|
Sep
|
Oct
|
Nov
(1) |
Dec
(9) |
2014 |
Jan
(2) |
Feb
(4) |
Mar
(4) |
Apr
(1) |
May
(4) |
Jun
(2) |
Jul
|
Aug
|
Sep
|
Oct
(2) |
Nov
|
Dec
(1) |
2015 |
Jan
(1) |
Feb
|
Mar
|
Apr
(6) |
May
(2) |
Jun
|
Jul
|
Aug
(1) |
Sep
|
Oct
|
Nov
|
Dec
|
2016 |
Jan
(3) |
Feb
(2) |
Mar
|
Apr
(3) |
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
2017 |
Jan
|
Feb
|
Mar
(1) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
(1) |
Oct
|
Nov
|
Dec
|
From: Mark H. <mha...@us...> - 2009-01-26 01:23:15
|
Update of /cvsroot/pywin32/pywin32/win32/test In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv11971/win32/test Modified Files: test_win32file.py Log Message: make new tests py3k-friendly Index: test_win32file.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_win32file.py,v retrieving revision 1.29 retrieving revision 1.30 diff -C2 -d -r1.29 -r1.30 *** test_win32file.py 26 Jan 2009 00:47:31 -0000 1.29 --- test_win32file.py 26 Jan 2009 01:23:09 -0000 1.30 *************** *** 595,599 **** cli, addr = s1.accept() self.request = cli.recv(1024) ! cli.send('some expected response') t = threading.Thread(target=runner) t.start() --- 595,599 ---- cli, addr = s1.accept() self.request = cli.recv(1024) ! cli.send(str2bytes('some expected response')) t = threading.Thread(target=runner) t.start() *************** *** 602,606 **** ol = pywintypes.OVERLAPPED() s2.bind(('0.0.0.0', 0)) # connectex requires the socket be bound beforehand ! win32file.ConnectEx(s2, self.addr, ol, "some expected request") win32file.GetOverlappedResult(s2.fileno(), ol, 1) ol = pywintypes.OVERLAPPED() --- 602,606 ---- ol = pywintypes.OVERLAPPED() s2.bind(('0.0.0.0', 0)) # connectex requires the socket be bound beforehand ! win32file.ConnectEx(s2, self.addr, ol, str2bytes("some expected request")) win32file.GetOverlappedResult(s2.fileno(), ol, 1) ol = pywintypes.OVERLAPPED() *************** *** 609,614 **** length = win32file.GetOverlappedResult(s2.fileno(), ol, 1) self.response = buff[:length] ! self.assertEqual(self.response, 'some expected response') ! self.assertEqual(self.request, 'some expected request') t.join(5) self.failIf(t.isAlive(), "worker thread didn't terminate") --- 609,614 ---- length = win32file.GetOverlappedResult(s2.fileno(), ol, 1) self.response = buff[:length] ! self.assertEqual(self.response, str2bytes('some expected response')) ! self.assertEqual(self.request, str2bytes('some expected request')) t.join(5) self.failIf(t.isAlive(), "worker thread didn't terminate") *************** *** 621,625 **** s1.listen(1) cli, addr = s1.accept() ! cli.send('some expected response') t = threading.Thread(target=runner) t.start() --- 621,625 ---- s1.listen(1) cli, addr = s1.accept() ! cli.send(str2bytes('some expected response')) t = threading.Thread(target=runner) t.start() *************** *** 635,639 **** length = win32file.GetOverlappedResult(s2.fileno(), ol, 1) self.response = buff[:length] ! self.assertEqual(self.response, 'some expected response') t.join(5) self.failIf(t.isAlive(), "worker thread didn't terminate") --- 635,639 ---- length = win32file.GetOverlappedResult(s2.fileno(), ol, 1) self.response = buff[:length] ! self.assertEqual(self.response, str2bytes('some expected response')) t.join(5) self.failIf(t.isAlive(), "worker thread didn't terminate") *************** *** 666,670 **** length = 0 ! ol = pywintypes.OVERLAPPED() f.seek(0) --- 666,674 ---- length = 0 ! aaa = str2bytes("[AAA]") ! bbb = str2bytes("[BBB]") ! ccc = str2bytes("[CCC]") ! ddd = str2bytes("[DDD]") ! empty = str2bytes("") ol = pywintypes.OVERLAPPED() f.seek(0) *************** *** 674,700 **** ol = pywintypes.OVERLAPPED() f.seek(0) ! win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0, "[AAA]", "[BBB]") length += win32file.GetOverlappedResult(s2.fileno(), ol, 1) ol = pywintypes.OVERLAPPED() f.seek(0) ! win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0, "", "") length += win32file.GetOverlappedResult(s2.fileno(), ol, 1) ol = pywintypes.OVERLAPPED() f.seek(0) ! win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0, None, "[CCC]") length += win32file.GetOverlappedResult(s2.fileno(), ol, 1) ol = pywintypes.OVERLAPPED() f.seek(0) ! win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0, "[DDD]") length += win32file.GetOverlappedResult(s2.fileno(), ol, 1) s2.close() th.join() ! buf = ''.join(self.request) self.assertEqual(length, len(buf)) ! self.assert_(("%s[AAA]%s[BBB]%s%s[CCC][DDD]%s" % (val,val,val,val,val)) == buf) --- 678,706 ---- ol = pywintypes.OVERLAPPED() f.seek(0) ! win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0, aaa, bbb) length += win32file.GetOverlappedResult(s2.fileno(), ol, 1) ol = pywintypes.OVERLAPPED() f.seek(0) ! win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0, empty, empty) length += win32file.GetOverlappedResult(s2.fileno(), ol, 1) ol = pywintypes.OVERLAPPED() f.seek(0) ! win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0, None, ccc) length += win32file.GetOverlappedResult(s2.fileno(), ol, 1) ol = pywintypes.OVERLAPPED() f.seek(0) ! win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0, ddd) length += win32file.GetOverlappedResult(s2.fileno(), ol, 1) s2.close() th.join() ! buf = str2bytes('').join(self.request) self.assertEqual(length, len(buf)) ! expected = val + aaa + val + bbb + val + val + ccc + ddd + val ! self.assertEqual(type(expected), type(buf)) ! self.assert_(expected == buf) |
From: Mark H. <mha...@us...> - 2009-01-26 00:47:37
|
Update of /cvsroot/pywin32/pywin32/win32/src In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv4651/win32/src Modified Files: PyTime.cpp PyWinTypes.h win32file.i Log Message: Merge optional support for using datetime objects from py3k-integration branch. Currently must be enabled at build time and only currently enabled for py3k (although it does work with all versions >= 2.4) Index: PyTime.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/PyTime.cpp,v retrieving revision 1.24 retrieving revision 1.25 diff -C2 -d -r1.24 -r1.25 *** PyTime.cpp 9 Jan 2009 01:27:44 -0000 1.24 --- PyTime.cpp 26 Jan 2009 00:47:31 -0000 1.25 *************** *** 5,18 **** #include "PyWinTypes.h" #include "PyWinObjects.h" #include "time.h" #include "tchar.h" ! static WORD SequenceIndexAsWORD(PyObject *seq, int index) ! { ! PyObject *t = PySequence_GetItem(seq, index); ! int ret = t ? PyInt_AsLong(t) : -1; ! Py_XDECREF(t); ! return (WORD)ret; ! } BOOL PyWinTime_Check(PyObject *ob) --- 5,17 ---- #include "PyWinTypes.h" #include "PyWinObjects.h" + + #ifdef PYWIN_HAVE_DATETIME_CAPI + #include "datetime.h" // python's datetime header. + #endif + #include "time.h" #include "tchar.h" ! PyObject *PyWin_NewTime(PyObject *timeOb); BOOL PyWinTime_Check(PyObject *ob) *************** *** 22,98 **** PyWinTime_CHECK(ob) || #endif PyObject_HasAttrString(ob, "timetuple"); } ! PyObject *PyWin_NewTime(PyObject *timeOb) { ! // If it already a datetime object, just return it as-is. ! if (PyWinTime_CHECK(timeOb)) { ! Py_INCREF(timeOb); ! return timeOb; ! } ! ! PyObject *result = NULL; ! /***** Commented out temporarily ! if ( PyFloat_Check(timeOb) ) ! { ! result = new PyTime(PyFloat_AS_DOUBLE((PyFloatObject *)timeOb)); ! } ! else *****/ ! PyObject *cleanupOb = NULL; // must be xdefref'd. ! // Support objects with a "timetuple" method. ! PyObject *method = PyObject_GetAttrString(timeOb, "timetuple"); ! if (method==NULL) ! PyErr_Clear(); ! else { ! timeOb = PyEval_CallObject(method, NULL); ! Py_DECREF(method); ! if (!timeOb) return NULL; ! cleanupOb = timeOb; // new reference that must be nuked. ! // now we should fall into the sequence check! ! } ! if ( PyNumber_Check(timeOb) ) ! { ! // XXX - should possibly check for long_long, as sizeof(time_t) > sizeof(long) ! // on x64 ! long t = PyInt_AsLong(timeOb); ! if ( t == -1 ) ! { ! if ( !PyErr_Occurred() ) ! PyErr_BadArgument(); ! } else ! result = new PyTime((time_t)t); ! } ! else if ( PySequence_Check(timeOb) ) ! { ! PyErr_Clear(); // ensure stale errors don't trip us. ! if (PySequence_Length(timeOb) < 6) ! { ! Py_XDECREF(cleanupOb); ! return PyErr_Format(PyExc_ValueError, "time tuple must have at least 6 elements"); } ! SYSTEMTIME st = { ! SequenceIndexAsWORD(timeOb, 0), ! SequenceIndexAsWORD(timeOb, 1), ! 0, ! SequenceIndexAsWORD(timeOb, 2), ! SequenceIndexAsWORD(timeOb, 3), ! SequenceIndexAsWORD(timeOb, 4), ! SequenceIndexAsWORD(timeOb, 5), ! 0 ! }; ! // A Python time tuple has 9 entries. We allow a 10th to specify ms ! if (PySequence_Length(timeOb) > 9) ! st.wMilliseconds = SequenceIndexAsWORD(timeOb, 9); ! if ( !PyErr_Occurred() ) ! result = new PyTime(st); } ! else ! // result stays NULL. ! PyErr_Format(PyExc_TypeError, "Objects of type '%s' can not be used as a time object", ! timeOb->ob_type->tp_name); ! Py_XDECREF(cleanupOb); ! return result; } --- 21,56 ---- PyWinTime_CHECK(ob) || #endif + #ifdef PYWIN_HAVE_DATETIME_CAPI + PyDateTime_Check(ob) || + #endif PyObject_HasAttrString(ob, "timetuple"); } ! // Timezone helpers... ! // Returns a timezone object representing UTC. Implementation currently ! // calls into win32timezone for an object then caches it forever. ! static PyObject *GetTZUTC() { ! static PyObject *got = NULL; ! if (got==NULL) { ! // assumes we have the gil so no races... ! PyObject *mod = PyImport_ImportModule("win32timezone"); ! if (!mod) return NULL; ! PyObject *klass = PyObject_GetAttrString(mod, "TimeZoneInfo"); ! Py_DECREF(mod); ! if (!klass) ! return NULL; ! PyObject *args = PyTuple_New(0); ! if (args) { ! got = PyObject_CallMethod(klass, "utc", ""); ! Py_DECREF(args); } ! Py_DECREF(klass); ! assert(got); ! assert(got != Py_None); // this would silently create a tz-naive object. } ! Py_XINCREF(got); ! return got; } *************** *** 112,141 **** } ! PyObject *PyWinObject_FromSYSTEMTIME(const SYSTEMTIME &t) ! { ! return new PyTime(t); ! } ! PyObject *PyWinObject_FromFILETIME(const FILETIME &t) ! { ! return new PyTime(t); ! } ! PyObject *PyWinObject_FromDATE(DATE t) ! { ! return new PyTime(t); ! } ! PyObject *PyWinTimeObject_Fromtime_t(time_t t) ! { ! return new PyTime(t); ! } ! ! // Converts a TimeStamp, which is in 100 nanosecond units like a FILETIME ! // See comments in pywintypes.h re LARGE_INTEGER vs TimeStamp ! PyObject *PyWinObject_FromTimeStamp(const LARGE_INTEGER &ts) ! { ! FILETIME ft; ! ft.dwHighDateTime=ts.HighPart; ! ft.dwLowDateTime=ts.LowPart; ! return new PyTime(ft); ! } BOOL PyWinObject_AsDATE(PyObject *ob, DATE *pDate) --- 70,74 ---- } ! #ifndef NO_PYWINTYPES_TIME BOOL PyWinObject_AsDATE(PyObject *ob, DATE *pDate) *************** *** 180,191 **** } - - #define SECS_PER_DAY (24.0 * 60.0 * 60.0) - - #ifndef MS_WINCE - /* the following code is taken from Python 2.3 Modules/datetimemodule.c * it is used for calculating day of the year for PyTime::Format */ static int _days_before_month[] = { --- 113,120 ---- } /* the following code is taken from Python 2.3 Modules/datetimemodule.c * it is used for calculating day of the year for PyTime::Format */ + #define SECS_PER_DAY (24.0 * 60.0 * 60.0) static int _days_before_month[] = { *************** *** 748,754 **** --- 677,1063 ---- #endif // NO_PYWINTYPES_TIME + /////////////////////////////////////////////////////////////////////////// + // + // The pywin32 time API using datetime objects + // + /////////////////////////////////////////////////////////////////////////// + #ifdef PYWIN_HAVE_DATETIME_CAPI + // @object PyDateTime|A Python object, representing an instant in time. + // @desc pywin32 builds for Python 3.0 use datetime objects instead of the + // old PyTime object. + // @desc PyDateTime is a sub-class of the regular datetime.datetime object. + // It is subclassed so it can provide a somewhat backwards compatible + // <om PyDateTime.Format> method, but is otherwise identical. + + // @method str|PyDateTime|Format| + // @desc This method is an alias for the datetime strftime method, using + // %c as the default value for the format string. + static PyObject *PyWinDateTimeType_Format(PyObject *self, PyObject *args) + { + PyObject *new_args = NULL; + PyObject *method = NULL; + PyObject *ret = NULL; + if (PyTuple_Size(args)==0) { + if (!(new_args = Py_BuildValue("(s)", "%c"))) + return NULL; + args = new_args; + } + if (!(method=PyObject_GetAttrString(self, "strftime"))) + goto done; + + ret = PyObject_Call(method, args, NULL); + done: + Py_XDECREF(new_args); + Py_XDECREF(method); + return ret; + } + + struct PyMethodDef PyWinDateTimeType_methods[] = { + {"Format", PyWinDateTimeType_Format, 1}, // @pymeth Format|Formats the time value - an alias for strftime with a default param. + {NULL} + }; + + // we sub-class the datetime.datetime object so we can provide a b/w compat + // 'Format' method. + // Note that this is a temporary strategy - 'Format()' will soon become + // deprecated - but we must give some period for people to adjust before + // breaking this fundamental method. + PyTypeObject PyWinDateTimeType = + { + PYWIN_OBJECT_HEAD + "pywintypes.datetime", + 0, // tp_basicsize filled in at runtime + 0, + // dealloc filled at runtime + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + PyWinDateTimeType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + // we fill tp_base in at runtime; its not available statically. + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + // tp_new filled at runtime + 0, /* tp_new */ + }; + + BOOL PyWinObject_AsDATE(PyObject *ob, DATE *pDate) + { + SYSTEMTIME st; + if (!PyWinObject_AsSYSTEMTIME(ob, &st)) + return FALSE; + if (!SystemTimeToVariantTime(&st, pDate)) { + PyWin_SetAPIError("SystemTimeToVariantTime"); + return FALSE; + } + return TRUE; + } + + BOOL PyWinObject_AsFILETIME(PyObject *ob, FILETIME *ft) + { + SYSTEMTIME st; + if (!PyWinObject_AsSYSTEMTIME(ob, &st)) + return FALSE; + // and to the FILETIME + if (!SystemTimeToFileTime(&st, ft)) { + PyWin_SetAPIError("SystemTimeToFileTime"); + return FALSE; + } + return TRUE; + } + + BOOL PyWinObject_AsSYSTEMTIME(PyObject *ob, SYSTEMTIME *st) + { + if (!PyDateTime_Check(ob)) { + PyErr_Format(PyExc_TypeError, "must be a pywintypes time object (got %s)", + ob->ob_type->tp_name); + return NULL; + } + // convert the date to a UTC date. + PyObject *utc = PyObject_CallMethod(ob, "astimezone", "O", GetTZUTC()); + // likely error is "ValueError: astimezone() cannot be applied to a naive datetime" + if (!utc) + return NULL; + st->wYear = PyDateTime_GET_YEAR(utc); + st->wMonth = PyDateTime_GET_MONTH(utc); + st->wDay = PyDateTime_GET_DAY(utc); + st->wHour = PyDateTime_DATE_GET_HOUR(utc); + st->wMinute = PyDateTime_DATE_GET_MINUTE(utc); + st->wSecond = PyDateTime_DATE_GET_SECOND(utc); + st->wMilliseconds = PyDateTime_DATE_GET_MICROSECOND(utc) / 1000; + Py_DECREF(utc); + return TRUE; + } + + #endif // PYWIN_HAVE_DATETIME_CAPI + + // a slightly modified version from Python's time module. + static BOOL + gettmarg(PyObject *ob, struct tm *p, int *pmsec) + { + int y; + memset((void *) p, '\0', sizeof(struct tm)); + + if (!PyArg_ParseTuple(ob, "iiiiiiiii|i", + &y, + &p->tm_mon, + &p->tm_mday, + &p->tm_hour, + &p->tm_min, + &p->tm_sec, + &p->tm_wday, + &p->tm_yday, + &p->tm_isdst, + pmsec)) + return FALSE; + if (y < 1900) { + // we always accept 2digit years + if (69 <= y && y <= 99) + y += 1900; + else if (0 <= y && y <= 68) + y += 2000; + else { + PyErr_SetString(PyExc_ValueError, + "year out of range"); + return FALSE; + } + } + p->tm_year = y - 1900; + p->tm_mon--; + p->tm_wday = (p->tm_wday + 1) % 7; + p->tm_yday--; + return TRUE; + } + + static WORD SequenceIndexAsWORD(PyObject *seq, int index) + { + PyObject *t = PySequence_GetItem(seq, index); + int ret = t ? PyInt_AsLong(t) : -1; + Py_XDECREF(t); + return (WORD)ret; + } + + PyObject *PyWin_NewTime(PyObject *timeOb) + { + // If it already a datetime object, just return it as-is. + #ifndef NO_PYWINTYPES_TIME + if (PyWinTime_CHECK(timeOb)) { + #endif + #ifdef PYWIN_HAVE_DATETIME_CAPI + if (PyDateTime_Check(timeOb)) { + #endif + Py_INCREF(timeOb); + return timeOb; + } + + PyObject *result = NULL; + PyObject *cleanupOb = NULL; // must be xdefref'd. + + // Support other objects with a "timetuple" method. + PyObject *method = PyObject_GetAttrString(timeOb, "timetuple"); + if (method==NULL) + PyErr_Clear(); + else { + timeOb = PyEval_CallObject(method, NULL); + Py_DECREF(method); + if (!timeOb) + return NULL; + cleanupOb = timeOb; // new reference that must be nuked. + // now we should fall into the sequence check! + } + if ( PyNumber_Check(timeOb) ) + { + // XXX - should possibly check for long_long, as sizeof(time_t) > sizeof(long) + // on x64 + long t = PyInt_AsLong(timeOb); + if ( t == -1 ) + { + if ( !PyErr_Occurred() ) + PyErr_BadArgument(); + } else + result = PyWinTimeObject_Fromtime_t((time_t)t); + } + else if ( PySequence_Check(timeOb) ) + { + assert(!PyErr_Occurred()); // should be no stale errors! + #ifdef PYWIN_HAVE_DATETIME_CAPI + // convert a timetuple, with optional millisecond extension, + // into a datetime object. ie: + // >>> datetime.datetime.fromtimestamp(time.mktime(timetuple)) + // but we 'inline' the time.mktime step... + struct tm buf; + time_t tt; + int millisec=0; + // must use a tuple as we use ParseTuple with an optional arg. + PyObject *tuple_args = PySequence_Tuple(timeOb); + if (!tuple_args) + return NULL; + BOOL ok = gettmarg(tuple_args, &buf, &millisec); + Py_DECREF(tuple_args); + if (!ok) + return NULL; + tt = mktime(&buf); + if (tt == (time_t)(-1)) { + PyErr_SetString(PyExc_OverflowError, + "mktime argument out of range"); + return NULL; + } + double dval = (double)tt + (millisec / 1000.0); + PyObject *args = Py_BuildValue("(d)", dval); + if (!args) + return NULL; + result = PyDateTimeAPI->DateTime_FromTimestamp( + (PyObject*)(&PyWinDateTimeType), args, NULL); + Py_DECREF(args); + #else + // Let's try and convert to a SYSTEMTIME and convert from + // there (which is what pywintypes always did pre datetime) + if (PySequence_Length(timeOb) < 6) + { + Py_XDECREF(cleanupOb); + return PyErr_Format(PyExc_ValueError, "time tuple must have at least 6 elements"); + } + SYSTEMTIME st = { + SequenceIndexAsWORD(timeOb, 0), + SequenceIndexAsWORD(timeOb, 1), + 0, + SequenceIndexAsWORD(timeOb, 2), + SequenceIndexAsWORD(timeOb, 3), + SequenceIndexAsWORD(timeOb, 4), + SequenceIndexAsWORD(timeOb, 5), + 0 + }; + // A Python time tuple has 9 entries. We allow a 10th to specify ms + if (PySequence_Length(timeOb) > 9) + st.wMilliseconds = SequenceIndexAsWORD(timeOb, 9); + if ( !PyErr_Occurred() ) + result = PyWinObject_FromSYSTEMTIME(st); + #endif // PYWIN_HAVE_DATETIME_CAPI + } + else + // result stays NULL. + PyErr_Format(PyExc_TypeError, "Objects of type '%s' can not be used as a time object", + timeOb->ob_type->tp_name); + Py_XDECREF(cleanupOb); + return result; + } + + PyObject *PyWinObject_FromSYSTEMTIME(const SYSTEMTIME &t) + { + #ifdef PYWIN_HAVE_DATETIME_CAPI + // SYSTEMTIME structures explicitly use UTC. + PyObject *obtz = GetTZUTC(); + if (!obtz) + return NULL; + PyObject *ret = PyDateTimeAPI->DateTime_FromDateAndTime( + t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, + t.wSecond, t.wMilliseconds*1000, + obtz, &PyWinDateTimeType); + Py_DECREF(obtz); + return ret; + #endif // PYWIN_HAVE_DATETIME_CAPI + + #ifndef NO_PYWINTYPES_TIME + return new PyTime(t); + #endif + } + + PyObject *PyWinObject_FromFILETIME(const FILETIME &t) + { + #ifdef PYWIN_HAVE_DATETIME_CAPI + // XXX - We should create a datetime object using the localtz here, + // but for now we only have a utc tz available, so convert to a + // systemtime and go from there. + SYSTEMTIME st; + if (!FileTimeToSystemTime(&t, &st)) + return PyWin_SetAPIError("FileTimeToSystemTime"); + return PyWinObject_FromSYSTEMTIME(st); + #endif // PYWIN_HAVE_DATETIME_CAPI + + #ifndef NO_PYWINTYPES_TIME + return new PyTime(t); + #endif + } + PyObject *PyWinObject_FromDATE(DATE t) + { + #ifdef PYWIN_HAVE_DATETIME_CAPI + SYSTEMTIME st; + if (!VariantTimeToSystemTime(t, &st)) + return PyWin_SetAPIError("VariantTimeToSystemTime"); + return PyWinObject_FromSYSTEMTIME(st); + #endif // PYWIN_HAVE_DATETIME_CAPI + + #ifndef NO_PYWINTYPES_TIME + return new PyTime(t); + #endif + } + + PyObject *PyWinTimeObject_Fromtime_t(time_t t) + { + #ifdef PYWIN_HAVE_DATETIME_CAPI + PyObject *args = Py_BuildValue("(i)", (int)t); + if (!args) + return NULL; + PyObject *ret = PyDateTimeAPI->DateTime_FromTimestamp( + (PyObject*)(&PyWinDateTimeType), args, NULL); + Py_DECREF(args); + return ret; + #endif // PYWIN_HAVE_DATETIME_CAPI + + #ifndef NO_PYWINTYPES_TIME + return new PyTime(t); + #endif + } + + // Converts a TimeStamp, which is in 100 nanosecond units like a FILETIME + // See comments in pywintypes.h re LARGE_INTEGER vs TimeStamp + PyObject *PyWinObject_FromTimeStamp(const LARGE_INTEGER &ts) + { + FILETIME ft; + ft.dwHighDateTime=ts.HighPart; + ft.dwLowDateTime=ts.LowPart; + return PyWinObject_FromFILETIME(ft); + } + // A couple of public functions used by the module init BOOL _PyWinDateTime_Init() { + #ifdef PYWIN_HAVE_DATETIME_CAPI + PyDateTime_IMPORT; + if (!PyDateTimeAPI) + return NULL; + PyWinDateTimeType.tp_base = PyDateTimeAPI->DateTimeType; + PyWinDateTimeType.tp_basicsize = PyDateTimeAPI->DateTimeType->tp_basicsize; + PyWinDateTimeType.tp_new = PyDateTimeAPI->DateTimeType->tp_new; + PyWinDateTimeType.tp_dealloc = PyDateTimeAPI->DateTimeType->tp_dealloc; + if (PyType_Ready(&PyWinDateTimeType) == -1) + return FALSE; + #endif return TRUE; } *************** *** 761,764 **** --- 1070,1078 ---- return FALSE; #endif + + #ifdef PYWIN_HAVE_DATETIME_CAPI + if (PyDict_SetItemString(dict, "TimeType", (PyObject *)&PyWinDateTimeType) == -1) + return FALSE; + #endif return TRUE; } Index: PyWinTypes.h =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/PyWinTypes.h,v retrieving revision 1.61 retrieving revision 1.62 diff -C2 -d -r1.61 -r1.62 *** PyWinTypes.h 26 Jan 2009 00:12:35 -0000 1.61 --- PyWinTypes.h 26 Jan 2009 00:47:31 -0000 1.62 *************** *** 494,498 **** // The NO_PYWINTYPES_TIME define was initially used for CE builds. We now // use that symbol to mean "do we include our old, crap, custom time object?" ! // This is currently always true on the trunk - but not for long :) PYWINTYPES_EXPORT PyObject *PyWinObject_FromSYSTEMTIME(const SYSTEMTIME &t); PYWINTYPES_EXPORT PyObject *PyWinObject_FromFILETIME(const FILETIME &t); --- 494,520 ---- // The NO_PYWINTYPES_TIME define was initially used for CE builds. We now // use that symbol to mean "do we include our old, crap, custom time object?" ! // If not defined, we exclusively support datetime objects via the C API. ! // (Note py2.3 doesn't have a C API, so will not currently build with ! // NO_PYWINTYPES_TIME defined.) ! // TODO: If both builtin and datetime objects are enabled, we will enable ! // some transitional period using something like ! // pywintypes.__future_datatime__, but for now this is defined purely at build ! // time. ! #if (PY_VERSION_HEX >= 0x03000000) ! # define NO_PYWINTYPES_TIME ! #endif ! ! // Python 2.3 doesn't have C Api for datetime, so can't have our new funky ! // support. ! #if (PY_VERSION_HEX >= 0x02040000) ! # define PYWIN_HAVE_DATETIME_CAPI ! #endif ! ! // XXX - fixme - ack - we don't yet like *both* defines existing - and for now ! // its only enabled in py3k ! #if (PY_VERSION_HEX < 0x03000000) ! # undef PYWIN_HAVE_DATETIME_CAPI ! #endif ! PYWINTYPES_EXPORT PyObject *PyWinObject_FromSYSTEMTIME(const SYSTEMTIME &t); PYWINTYPES_EXPORT PyObject *PyWinObject_FromFILETIME(const FILETIME &t); Index: win32file.i =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/win32file.i,v retrieving revision 1.98 retrieving revision 1.99 diff -C2 -d -r1.98 -r1.99 *** win32file.i 25 Jan 2009 23:50:53 -0000 1.98 --- win32file.i 26 Jan 2009 00:47:31 -0000 1.99 *************** *** 51,54 **** --- 51,59 ---- %{ + + #ifdef PYWIN_HAVE_DATETIME_CAPI + #include "datetime.h" // python's datetime header. + #endif + // older python version's don't get the PyCObject structure definition // exposed, and we need it to cleanly zap our handles (see *************** *** 675,678 **** --- 680,693 ---- %{ + // Helper for SetFileTime - see comments below. + static BOOL PyWinTime_DateTimeCheck(PyObject *ob) + { + return FALSE + #ifdef PYWIN_HAVE_DATETIME_CAPI + || (PyDateTimeAPI && PyDateTime_Check(ob)) + #endif + ; + } + // @pyswig None|SetFileTime|Sets the date and time that a file was created, last accessed, or last modified. static PyObject *PySetFileTime (PyObject *self, PyObject *args) *************** *** 700,704 **** if (!PyWinObject_AsFILETIME(obTimeCreated, &LocalFileTime)) return NULL; ! LocalFileTimeToFileTime(&LocalFileTime, &TimeCreated); lpTimeCreated= &TimeCreated; } --- 715,725 ---- if (!PyWinObject_AsFILETIME(obTimeCreated, &LocalFileTime)) return NULL; ! // This sucks! This code is the only code in pywin32 that ! // blindly converted the result of AsFILETIME to a localtime. ! // That doesn't make sense in a tz-aware datetime world... ! if (PyWinTime_DateTimeCheck(obTimeCreated)) ! TimeCreated = LocalFileTime; ! else ! LocalFileTimeToFileTime(&LocalFileTime, &TimeCreated); lpTimeCreated= &TimeCreated; } *************** *** 709,713 **** if (!PyWinObject_AsFILETIME(obTimeAccessed, &LocalFileTime)) return NULL; ! LocalFileTimeToFileTime(&LocalFileTime, &TimeAccessed); lpTimeAccessed= &TimeAccessed; } --- 730,737 ---- if (!PyWinObject_AsFILETIME(obTimeAccessed, &LocalFileTime)) return NULL; ! if (PyWinTime_DateTimeCheck(obTimeAccessed)) ! TimeAccessed = LocalFileTime; ! else ! LocalFileTimeToFileTime(&LocalFileTime, &TimeAccessed); lpTimeAccessed= &TimeAccessed; } *************** *** 718,722 **** if (!PyWinObject_AsFILETIME(obTimeWritten, &LocalFileTime)) return NULL; ! LocalFileTimeToFileTime(&LocalFileTime, &TimeWritten); lpTimeWritten= &TimeWritten; } --- 742,749 ---- if (!PyWinObject_AsFILETIME(obTimeWritten, &LocalFileTime)) return NULL; ! if (PyWinTime_DateTimeCheck(obTimeWritten)) ! TimeWritten = LocalFileTime; ! else ! LocalFileTimeToFileTime(&LocalFileTime, &TimeWritten); lpTimeWritten= &TimeWritten; } *************** *** 5240,5243 **** --- 5267,5274 ---- PYWIN_MODULE_INIT_RETURN_ERROR; + #ifdef PYWIN_HAVE_DATETIME_CAPI + PyDateTime_IMPORT; + #endif + for (PyMethodDef *pmd = win32fileMethods;pmd->ml_name;pmd++) if ((strcmp(pmd->ml_name, "CreateFileW")==0) |
From: Mark H. <mha...@us...> - 2009-01-26 00:47:37
|
Update of /cvsroot/pywin32/pywin32/win32/test In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv4651/win32/test Modified Files: test_win32api.py test_win32file.py Log Message: Merge optional support for using datetime objects from py3k-integration branch. Currently must be enabled at build time and only currently enabled for py3k (although it does work with all versions >= 2.4) Index: test_win32file.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_win32file.py,v retrieving revision 1.28 retrieving revision 1.29 diff -C2 -d -r1.28 -r1.29 *** test_win32file.py 25 Jan 2009 23:50:53 -0000 1.28 --- test_win32file.py 26 Jan 2009 00:47:31 -0000 1.29 *************** *** 3,6 **** --- 3,7 ---- import win32api, win32file, win32pipe, pywintypes, winerror, win32event import win32con, ntsecuritycon + import win32timezone import sys import os *************** *** 122,125 **** --- 123,153 ---- os.unlink(filename) + def testFileTimesTimezones(self): + if not issubclass(pywintypes.TimeType, datetime.datetime): + # maybe should report 'skipped', but that's not quite right as + # there is nothing you can do to avoid it being skipped! + return + filename = tempfile.mktemp("-testFileTimes") + now_utc = win32timezone.utcnow() + now_local = now_utc.astimezone(win32timezone.TimeZoneInfo.local()) + h = win32file.CreateFile(filename, + win32file.GENERIC_READ|win32file.GENERIC_WRITE, + 0, None, win32file.CREATE_ALWAYS, 0, 0) + try: + win32file.SetFileTime(h, now_utc, now_utc, now_utc) + ct, at, wt = win32file.GetFileTime(h) + self.failUnlessEqual(now_local, ct) + self.failUnlessEqual(now_local, at) + self.failUnlessEqual(now_local, wt) + # and the reverse - set local, check against utc + win32file.SetFileTime(h, now_local, now_local, now_local) + ct, at, wt = win32file.GetFileTime(h) + self.failUnlessEqual(now_utc, ct) + self.failUnlessEqual(now_utc, at) + self.failUnlessEqual(now_utc, wt) + finally: + h.close() + os.unlink(filename) + def testFileTimes(self): if issubclass(pywintypes.TimeType, datetime.datetime): Index: test_win32api.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_win32api.py,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** test_win32api.py 7 Jan 2009 06:03:29 -0000 1.16 --- test_win32api.py 26 Jan 2009 00:47:31 -0000 1.17 *************** *** 7,10 **** --- 7,11 ---- import sys, os import tempfile + import datetime class CurrentUserTestCase(unittest.TestCase): *************** *** 25,29 **** # for the sake of code exercise but don't output tz_str.encode() ! tz_time.Format() def TestDateFormat(self): DATE_LONGDATE = 2 --- 26,31 ---- # for the sake of code exercise but don't output tz_str.encode() ! if not isinstance(tz_time, datetime.datetime): ! tz_time.Format() def TestDateFormat(self): DATE_LONGDATE = 2 |
From: Mark H. <mha...@us...> - 2009-01-26 00:47:37
|
Update of /cvsroot/pywin32/pywin32/com/win32com/test In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv4651/com/win32com/test Modified Files: testPyComTest.py testShell.py Log Message: Merge optional support for using datetime objects from py3k-integration branch. Currently must be enabled at build time and only currently enabled for py3k (although it does work with all versions >= 2.4) Index: testShell.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/test/testShell.py,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** testShell.py 14 Jan 2009 04:43:56 -0000 1.14 --- testShell.py 26 Jan 2009 00:47:31 -0000 1.15 *************** *** 3,6 **** --- 3,8 ---- import unittest import copy + import datetime + import win32timezone try: *************** *** 11,14 **** --- 13,17 ---- import win32con import pythoncom + import pywintypes from win32com.shell import shell from win32com.shell.shellcon import * *************** *** 98,101 **** --- 101,115 ---- class FILEGROUPDESCRIPTORTester(win32com.test.util.TestCase): + def _getTestTimes(self): + if issubclass(pywintypes.TimeType, datetime.datetime): + ctime = win32timezone.now() + atime = ctime + datetime.timedelta(seconds=1) + wtime = atime + datetime.timedelta(seconds=1) + else: + ctime = pywintypes.Time(11) + atime = pywintypes.Time(12) + wtime = pywintypes.Time(13) + return ctime, atime, wtime + def _testRT(self, fd): fgd_string = shell.FILEGROUPDESCRIPTORAsString([fd]) *************** *** 136,139 **** --- 150,154 ---- return clsid = pythoncom.MakeIID("{CD637886-DB8B-4b04-98B5-25731E1495BE}") + ctime, atime, wtime = self._getTestTimes() d = dict(cFileName="foo.txt", clsid=clsid, *************** *** 141,147 **** pointl=(3,4), dwFileAttributes = win32con.FILE_ATTRIBUTE_NORMAL, ! ftCreationTime=pythoncom.MakeTime(10), ! ftLastAccessTime=pythoncom.MakeTime(11), ! ftLastWriteTime=pythoncom.MakeTime(12), nFileSize=sys_maxsize + 1) self._testRT(d) --- 156,162 ---- pointl=(3,4), dwFileAttributes = win32con.FILE_ATTRIBUTE_NORMAL, ! ftCreationTime=ctime, ! ftLastAccessTime=atime, ! ftLastWriteTime=wtime, nFileSize=sys_maxsize + 1) self._testRT(d) *************** *** 152,162 **** # no kw-args to dict in 2.2 - not worth converting! return d = [dict(cFileName="foo.txt", sizel=(1,2), pointl=(3,4), dwFileAttributes = win32con.FILE_ATTRIBUTE_NORMAL, ! ftCreationTime=pythoncom.MakeTime(10), ! ftLastAccessTime=pythoncom.MakeTime(11), ! ftLastWriteTime=pythoncom.MakeTime(12), nFileSize=sys_maxsize + 1), dict(cFileName="foo2.txt", --- 167,179 ---- # no kw-args to dict in 2.2 - not worth converting! return + + ctime, atime, wtime = self._getTestTimes() d = [dict(cFileName="foo.txt", sizel=(1,2), pointl=(3,4), dwFileAttributes = win32con.FILE_ATTRIBUTE_NORMAL, ! ftCreationTime=ctime, ! ftLastAccessTime=atime, ! ftLastWriteTime=wtime, nFileSize=sys_maxsize + 1), dict(cFileName="foo2.txt", *************** *** 164,170 **** pointl=(3,4), dwFileAttributes = win32con.FILE_ATTRIBUTE_NORMAL, ! ftCreationTime=pythoncom.MakeTime(10), ! ftLastAccessTime=pythoncom.MakeTime(11), ! ftLastWriteTime=pythoncom.MakeTime(12), nFileSize=sys_maxsize + 1), dict(cFileName=u"foo\xa9.txt", --- 181,187 ---- pointl=(3,4), dwFileAttributes = win32con.FILE_ATTRIBUTE_NORMAL, ! ftCreationTime=ctime, ! ftLastAccessTime=atime, ! ftLastWriteTime=wtime, nFileSize=sys_maxsize + 1), dict(cFileName=u"foo\xa9.txt", *************** *** 172,178 **** pointl=(3,4), dwFileAttributes = win32con.FILE_ATTRIBUTE_NORMAL, ! ftCreationTime=pythoncom.MakeTime(10), ! ftLastAccessTime=pythoncom.MakeTime(11), ! ftLastWriteTime=pythoncom.MakeTime(12), nFileSize=sys_maxsize + 1), ] --- 189,195 ---- pointl=(3,4), dwFileAttributes = win32con.FILE_ATTRIBUTE_NORMAL, ! ftCreationTime=ctime, ! ftLastAccessTime=atime, ! ftLastWriteTime=wtime, nFileSize=sys_maxsize + 1), ] Index: testPyComTest.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/test/testPyComTest.py,v retrieving revision 1.43 retrieving revision 1.44 diff -C2 -d -r1.43 -r1.44 *** testPyComTest.py 9 Jan 2009 01:24:54 -0000 1.43 --- testPyComTest.py 26 Jan 2009 00:47:31 -0000 1.44 *************** *** 4,8 **** import sys; sys.coinit_flags=0 # Must be free-threaded! import win32api, pythoncom, time ! import sys, os, win32com, win32com.client.connect from win32com.test.util import CheckClean from win32com.client import constants, DispatchBaseClass --- 4,9 ---- import sys; sys.coinit_flags=0 # Must be free-threaded! import win32api, pythoncom, time ! import pywintypes ! import os, win32com, win32com.client.connect from win32com.test.util import CheckClean from win32com.client import constants, DispatchBaseClass *************** *** 10,13 **** --- 11,16 ---- from win32com.test.util import RegisterPythonServer from pywin32_testutil import str2memory + import datetime + import win32timezone importMsg = "**** PyCOMTest is not installed ***\n PyCOMTest is a Python test specific COM client and server.\n It is likely this server is not installed on this machine\n To install the server, you must get the win32com sources\n and build it using MS Visual C++" *************** *** 171,181 **** # raise RuntimeError, o.paramProp(0) ! try: ! import datetime now = datetime.datetime.now() expect = pythoncom.MakeTime(now) TestApplyResult(o.EarliestDate, (now, now), expect) ! except ImportError: ! pass # py 2.2 - no datetime def TestGenerated(): --- 174,194 ---- # raise RuntimeError, o.paramProp(0) ! if issubclass(pywintypes.TimeType, datetime.datetime): ! # For now *all* times passed must be tz-aware. ! now = win32timezone.now() ! # but conversion to and from a VARIANT loses sub-second... ! now = now.replace(microsecond=0) ! later = now + datetime.timedelta(seconds=1) ! TestApplyResult(o.EarliestDate, (now, later), now) ! else: ! # old PyTime object ! now = pythoncom.MakeTime(time.gmtime(time.time())) ! later = pythoncom.MakeTime(time.gmtime(time.time()+1)) ! TestApplyResult(o.EarliestDate, (now, later), now) ! # But it can still *accept* tz-naive datetime objects... now = datetime.datetime.now() expect = pythoncom.MakeTime(now) TestApplyResult(o.EarliestDate, (now, now), expect) ! def TestGenerated(): *************** *** 298,311 **** TestConstant("StringTest", u"Hello Lo\xaeaine") ! now = pythoncom.MakeTime(time.gmtime(time.time())) ! later = pythoncom.MakeTime(time.gmtime(time.time()+1)) ! TestApplyResult(o.EarliestDate, (now, later), now) ! try: ! import datetime now = datetime.datetime.now() expect = pythoncom.MakeTime(now) TestApplyResult(o.EarliestDate, (now, now), expect) - except ImportError: - pass # py 2.2 - no datetime assert o.DoubleString("foo") == "foofoo" --- 311,330 ---- TestConstant("StringTest", u"Hello Lo\xaeaine") ! if issubclass(pywintypes.TimeType, datetime.datetime): ! # For now *all* times passed must be tz-aware. ! now = win32timezone.now() ! # but conversion to and from a VARIANT loses sub-second... ! now = now.replace(microsecond=0) ! later = now + datetime.timedelta(seconds=1) ! TestApplyResult(o.EarliestDate, (now, later), now) ! else: ! # old PyTime object ! now = pythoncom.MakeTime(time.gmtime(time.time())) ! later = pythoncom.MakeTime(time.gmtime(time.time()+1)) ! TestApplyResult(o.EarliestDate, (now, later), now) ! # But it can still *accept* tz-naive datetime objects... now = datetime.datetime.now() expect = pythoncom.MakeTime(now) TestApplyResult(o.EarliestDate, (now, now), expect) assert o.DoubleString("foo") == "foofoo" |
From: Mark H. <mha...@us...> - 2009-01-26 00:47:37
|
Update of /cvsroot/pywin32/pywin32/com/win32com/client In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv4651/com/win32com/client Modified Files: build.py Log Message: Merge optional support for using datetime objects from py3k-integration branch. Currently must be enabled at build time and only currently enabled for py3k (although it does work with all versions >= 2.4) Index: build.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/client/build.py,v retrieving revision 1.39 retrieving revision 1.40 diff -C2 -d -r1.39 -r1.40 *** build.py 25 Jan 2009 03:35:15 -0000 1.39 --- build.py 26 Jan 2009 00:47:31 -0000 1.40 *************** *** 24,27 **** --- 24,28 ---- from pywintypes import TimeType import winerror + import datetime # A string ending with a quote can not be safely triple-quoted. *************** *** 558,568 **** if inOut & pythoncom.PARAMFLAG_FHASDEFAULT: ! # hack for Unicode until it repr's better. val = defArgVal[2] if type(val) is TimeType: year=val.year; month=val.month; day=val.day; hour=val.hour; minute=val.minute; second=val.second; msec=val.msec return "pywintypes.Time((%(year)d, %(month)d, %(day)d, %(hour)d, %(minute)d, %(second)d,0,0,0,%(msec)d))" % locals() ! else: ! return repr(val) return None --- 559,573 ---- if inOut & pythoncom.PARAMFLAG_FHASDEFAULT: ! # times need special handling... val = defArgVal[2] + if isinstance(val, datetime.datetime): + # VARIANT <-> SYSTEMTIME conversions always lose any sub-second + # resolution, so just use a 'timetuple' here. + return repr(tuple(val.utctimetuple())) if type(val) is TimeType: + # must be the 'old' pywintypes time object... year=val.year; month=val.month; day=val.day; hour=val.hour; minute=val.minute; second=val.second; msec=val.msec return "pywintypes.Time((%(year)d, %(month)d, %(day)d, %(hour)d, %(minute)d, %(second)d,0,0,0,%(msec)d))" % locals() ! return repr(val) return None |
From: Mark H. <mha...@us...> - 2009-01-26 00:15:04
|
Update of /cvsroot/pywin32/pywin32/win32/src In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv2168/win32/src Modified Files: win32pipe.i win32popen.cpp Log Message: On py2k, win32pipe.popen* no longer support win95 hacks via w9xpopen, and on py3k these functions don't exist at all! From py3k branch. Index: win32popen.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/win32popen.cpp,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** win32popen.cpp 6 Jun 2007 05:44:46 -0000 1.10 --- win32popen.cpp 26 Jan 2009 00:14:53 -0000 1.11 *************** *** 4,7 **** --- 4,11 ---- #include "Python.h" + + // Not used in py3k + #if (PY_VERSION_HEX < 0x03000000) + #include "malloc.h" #include "io.h" *************** *** 11,17 **** #define DllExport _declspec(dllexport) - extern bool g_fUsingWin9x; - extern CHAR g_szModulePath[]; - // These tell _PyPopen() wether to return 1, 2, or 3 file objects. #define POPEN_1 1 --- 15,18 ---- *************** *** 178,207 **** if (!(x = GetEnvironmentVariable("COMSPEC", s1, i))) return FALSE; ! if (!g_fUsingWin9x) ! { ! x = i + strlen(s3) + strlen(cmdstring) + 1; ! s2 = (char *)_alloca(x); ! ZeroMemory(s2, x); ! sprintf(s2, "%s%s%s", s1, s3, cmdstring); ! } ! else ! { ! // ! // Oh gag, we're on Win9x. Use the workaround listed in ! // KB: Q150956 ! // ! x = i + strlen(s3) + strlen(cmdstring) + 1 + strlen(g_szModulePath) + ! strlen(szConsoleSpawn) + 1; ! s2 = (char *)_alloca(x); ! ZeroMemory(s2, x); ! sprintf( ! s2, ! "%s%s%s%s%s\"", ! g_szModulePath, ! szConsoleSpawn, ! s1, ! s3, ! cmdstring); ! } } // Could be an else here to try cmd.exe / command.com in the path --- 179,186 ---- if (!(x = GetEnvironmentVariable("COMSPEC", s1, i))) return FALSE; ! x = i + strlen(s3) + strlen(cmdstring) + 1; ! s2 = (char *)_alloca(x); ! ZeroMemory(s2, x); ! sprintf(s2, "%s%s%s", s1, s3, cmdstring); } // Could be an else here to try cmd.exe / command.com in the path *************** *** 645,646 **** --- 624,627 ---- return result; } + + #endif // PY_VERSION_HEX < 0x03000000 Index: win32pipe.i =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/win32pipe.i,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** win32pipe.i 7 Jun 2008 07:23:54 -0000 1.18 --- win32pipe.i 26 Jan 2009 00:14:53 -0000 1.19 *************** *** 20,126 **** static GetNamedPipeClientProcessIdfunc pfnGetNamedPipeClientSessionId = NULL; static GetNamedPipeClientProcessIdfunc pfnGetNamedPipeServerSessionId = NULL; - - - // Global used to determine if Win9x win32pipe hack is necessary. - bool g_fUsingWin9x; - CHAR g_szModulePath[_MAX_PATH + 2]; - HINSTANCE g_hInstance = NULL; - - ///////////////////////////////////////////////////////////////////////////// - // DLL Entry Point - - #ifndef BUILD_FREEZE - // Doesnt work for freeze - but in that case, g_hInstance - // remaims NULL, so GetModuleFileName(NULL) will be used - // and still give the answer we are after. - extern "C" - BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/) - { - if (dwReason == DLL_PROCESS_ATTACH) - g_hInstance = hInstance; - return TRUE; - } - #endif // BUILD_FREEZE - - static BOOL LoadModulePath(void) - { - DWORD cbModuleFilename; - CHAR *psz = NULL; - - // Note: GetModuleFileName will write nSize + 1 characters - // to get the null terminator. - cbModuleFilename = GetModuleFileName( - g_hInstance, - g_szModulePath, - sizeof(g_szModulePath) - 1); - if (0 == cbModuleFilename) - { - // hr = HRESULT_FROM_WIN32(GetLastError()); - // ErrorTrace(hr); - return FALSE; - } - - if ((sizeof(g_szModulePath) - 1) == cbModuleFilename) - { - // Note: This should never happen - // hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - // ErrorTrace(hr); - return FALSE; - } - - // Start from the end of the string and insert a '\0' after the first '\\' you find. - psz = g_szModulePath + strlen(g_szModulePath) - 1; - while (psz > g_szModulePath && *psz != '\\') - { - psz--; - } - - if (*psz == '\\') - { - psz++; - *psz = '\0'; - } - else - { - // Something wierd happened. :( - return FALSE; - } - return TRUE; - } - - %} %init %{ // All errors raised by this module are of this type. - Py_INCREF(PyWinExc_ApiError); PyDict_SetItemString(d, "error", PyWinExc_ApiError); ! // Setup g_fUsingWin9x and module path correctly... ! { ! LoadModulePath(); ! ! OSVERSIONINFO osvi; ! ! memset(&osvi, 0, sizeof(osvi)); ! osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); ! ! if (!GetVersionEx(&osvi)) ! { ! PyWin_SetAPIError("GetVersionEx"); ! } ! ! if (osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) ! { ! g_fUsingWin9x = TRUE; ! } ! else ! { ! g_fUsingWin9x = FALSE; ! } ! } ! HMODULE hmod=GetModuleHandle("Kernel32.dll"); if (!hmod) ! hmod=LoadLibrary("Kernel32.dll"); if (hmod){ pfnGetNamedPipeClientProcessId = (GetNamedPipeClientProcessIdfunc)GetProcAddress(hmod, "GetNamedPipeClientProcessId"); --- 20,32 ---- static GetNamedPipeClientProcessIdfunc pfnGetNamedPipeClientSessionId = NULL; static GetNamedPipeClientProcessIdfunc pfnGetNamedPipeServerSessionId = NULL; %} %init %{ // All errors raised by this module are of this type. PyDict_SetItemString(d, "error", PyWinExc_ApiError); ! HMODULE hmod=GetModuleHandle(_T("Kernel32.dll")); if (!hmod) ! hmod=LoadLibrary(_T("Kernel32.dll")); if (hmod){ pfnGetNamedPipeClientProcessId = (GetNamedPipeClientProcessIdfunc)GetProcAddress(hmod, "GetNamedPipeClientProcessId"); *************** *** 131,134 **** --- 37,41 ---- %} + %ifdef SWIG_PY2K %{ extern PyObject *PyPopen(PyObject *self, PyObject *args); *************** *** 150,153 **** --- 57,62 ---- %native(popen4) PyPopen4; + %endif // SWIG_PY2K + %native(GetNamedPipeHandleState) MyGetNamedPipeHandleState; *************** *** 353,362 **** if ((cbReadData!=(DWORD)-1) || !PyErr_Occurred()){ if (pOverlapped){ // guaranteed to be NULL on CE - PyBufferProcs *pb = NULL; obRet = PyBuffer_New(cbReadData); if (obRet==NULL) return NULL; ! pb = obRet->ob_type->tp_as_buffer; ! (*pb->bf_getwritebuffer)(obRet, 0, &readData); } else { obRet=PyString_FromStringAndSize(NULL, cbReadData); --- 262,272 ---- if ((cbReadData!=(DWORD)-1) || !PyErr_Occurred()){ if (pOverlapped){ // guaranteed to be NULL on CE obRet = PyBuffer_New(cbReadData); if (obRet==NULL) return NULL; ! // This shouldn't fail for buffer just created, but new buffer interface is screwy ... ! DWORD newbufsize; // maybe also check new buffer size matched requested size ? ! if (!PyWinObject_AsReadBuffer(obRet, &readData, &newbufsize)) ! return NULL; } else { obRet=PyString_FromStringAndSize(NULL, cbReadData); |
From: Mark H. <mha...@us...> - 2009-01-26 00:12:42
|
Update of /cvsroot/pywin32/pywin32/win32/src In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv2024/win32/src Modified Files: PyWinTypes.h PyWinTypesmodule.cpp Log Message: merge py3k compatibility macros from py3k branch Index: PyWinTypesmodule.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/PyWinTypesmodule.cpp,v retrieving revision 1.48 retrieving revision 1.49 diff -C2 -d -r1.48 -r1.49 *** PyWinTypesmodule.cpp 8 Jan 2009 02:56:17 -0000 1.48 --- PyWinTypesmodule.cpp 26 Jan 2009 00:12:35 -0000 1.49 *************** *** 32,35 **** --- 32,87 ---- #endif + + #if (PY_VERSION_HEX >= 0x03000000) + // For py3k, a function that returns new memoryview object instead of buffer. + // ??? Byte array object is mutable, maybe just use that directly as a substitute ??? + // Docs do not specify that you can pass NULL buffer to PyByteArray_FromStringAndSize, but it works + PyObject *PyBuffer_New(Py_ssize_t size){ + PyObject *bah = PyByteArray_FromStringAndSize(NULL, size); + if (bah==NULL) + return NULL; + PyObject *ret = PyMemoryView_FromObject(bah); + Py_DECREF(bah); // Memory view keeps its own ref to base object + return ret; + } + + PyObject *PyBuffer_FromReadWriteMemory(void *buf, Py_ssize_t size){ + // buf is not freed by returned object !!!!!!! + Py_buffer info={ + buf, + NULL, // obj added in 3.0b3 + size, + FALSE, // readonly + NULL, // format + 0, // ndim + NULL, // shape + NULL, // strided + NULL, // suboffsets + 0, // itemsize + NULL, // internal + }; + return PyMemoryView_FromBuffer(&info); + } + + PyObject *PyBuffer_FromMemory(void *buf, Py_ssize_t size){ + // buf is not freed by returned object !!!!!!! + Py_buffer info={ + buf, + NULL, // obj added in 3.0b3 + size, + TRUE, // readonly + NULL, // format + 0, // ndim + NULL, // shape + NULL, // strided + NULL, // suboffsets + 0, // itemsize + NULL, // internal + }; + return PyMemoryView_FromBuffer(&info); + } + #endif + + // See comments in pywintypes.h for why we need this! void PyWin_MakePendingCalls() *************** *** 878,881 **** --- 930,961 ---- // @tupleitem 3|None/int|argerror|The index of the argument in error, or (usually) None or -1 } + + /* PyType_Ready needs to be called anytime pywintypesxx.dll is loaded, since + other extension modules can use types defined here without pywintypes itself + having been imported. + ??? All extension modules that call this need to be changed to check the exit code ??? + */ + if (PyType_Ready(&PyHANDLEType) == -1 + ||PyType_Ready(&PyOVERLAPPEDType) == -1 + ||PyType_Ready(&PyDEVMODEType) == -1 + ||PyType_Ready(&PyDEVMODEWType) == -1 + ||PyType_Ready(&PyWAVEFORMATEXType) == -1 + #ifndef NO_PYWINTYPES_TIME + ||PyType_Ready(&PyTimeType) == -1 + #endif // NO_PYWINTYPES_TIME + #ifndef NO_PYWINTYPES_IID + ||PyType_Ready(&PyIIDType) == -1 + #endif // NO_PYWINTYPES_IID + #ifndef NO_PYWINTYPES_SECURITY + ||PyType_Ready(&PySECURITY_DESCRIPTORType) == -1 + ||PyType_Ready(&PySECURITY_ATTRIBUTESType) == -1 + ||PyType_Ready(&PySIDType) == -1 + ||PyType_Ready(&PyACLType) == -1 + #endif + ) + return -1; + + if (!_PyWinDateTime_Init()) + return -1; return 0; } Index: PyWinTypes.h =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/PyWinTypes.h,v retrieving revision 1.60 retrieving revision 1.61 diff -C2 -d -r1.60 -r1.61 *** PyWinTypes.h 8 Jan 2009 02:56:17 -0000 1.60 --- PyWinTypes.h 26 Jan 2009 00:12:35 -0000 1.61 *************** *** 131,135 **** */ #define PYWIN_ATTR_CONVERT _PyUnicode_AsString ! #endif // PY_VERSION_HEX // See PEP-353 - this is the "official" test... --- 131,157 ---- */ #define PYWIN_ATTR_CONVERT _PyUnicode_AsString ! ! /* Some API functions changed/removed in python 3.0 ! Definitions for the string functions are in stringobject.h, ! but comments indicate that this header is likely to go away in 3.1. ! */ ! #define PyString_Check PyBytes_Check ! #define PyString_Size PyBytes_Size ! #define PyString_AsString PyBytes_AsString ! #define PyString_AsStringAndSize PyBytes_AsStringAndSize ! #define PyString_FromString PyBytes_FromString ! #define PyString_FromStringAndSize PyBytes_FromStringAndSize ! #define _PyString_Resize _PyBytes_Resize ! #define PyString_AS_STRING PyBytes_AS_STRING ! #define PyString_GET_SIZE PyBytes_GET_SIZE ! #define PyString_Concat PyBytes_Concat ! #define PyInt_Check PyLong_Check ! #define PyInt_FromLong PyLong_FromLong ! #define PyInt_AsLong PyLong_AsLong ! #define PyInt_AS_LONG PyLong_AS_LONG ! #define PyInt_FromSsize_t PyLong_FromSsize_t ! #define PyInt_AsSsize_t PyLong_AsSsize_t ! #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask ! #endif // (PY_VERSION_HEX < 0x03000000) // See PEP-353 - this is the "official" test... |
From: Mark H. <mha...@us...> - 2009-01-26 00:11:21
|
Update of /cvsroot/pywin32/pywin32/Pythonwin/pywin/mfc In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv1916/Pythonwin/pywin/mfc Modified Files: dialog.py Log Message: add a comment about needing py3k support Index: dialog.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/Pythonwin/pywin/mfc/dialog.py,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** dialog.py 4 Dec 2008 07:00:21 -0000 1.9 --- dialog.py 26 Jan 2009 00:11:15 -0000 1.10 *************** *** 69,72 **** --- 69,73 ---- def items(self): return self.data.items() def values(self): return self.data.values() + # XXX - needs py3k work! def has_key(self, key): return key in self.data |
From: Mark H. <mha...@us...> - 2009-01-25 23:52:46
|
Update of /cvsroot/pywin32/pywin32 In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv32513 Modified Files: CHANGES.txt Log Message: recent changes Index: CHANGES.txt =================================================================== RCS file: /cvsroot/pywin32/pywin32/CHANGES.txt,v retrieving revision 1.41 retrieving revision 1.42 diff -C2 -d -r1.41 -r1.42 *** CHANGES.txt 2 Jan 2009 00:01:16 -0000 1.41 --- CHANGES.txt 25 Jan 2009 23:52:40 -0000 1.42 *************** *** 74,78 **** * win32com.shell gets support for IContextMenu2 and IContextMenu3 ! * add win32api.GetNativeSystemInfo(), win32api.GetKeyboardLayout() Since build 211: --- 74,82 ---- * win32com.shell gets support for IContextMenu2 and IContextMenu3 ! * add win32api.GetNativeSystemInfo(), win32api.GetKeyboardLayout(), ! win32api.GetPwrCapabilities. ! ! * add win32file.ConnectEx() and win32file.TransmitFile() (ionel and Roger via ! [1962146]) Since build 211: |
From: Mark H. <mha...@us...> - 2009-01-25 23:51:01
|
Update of /cvsroot/pywin32/pywin32/win32/test In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv32317/win32/test Modified Files: test_win32file.py Log Message: Merge win32file.ConnectEx and TransmitFile changes from [1962146], via Roger on the py3k branch. Index: test_win32file.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_win32file.py,v retrieving revision 1.27 retrieving revision 1.28 diff -C2 -d -r1.27 -r1.28 *** test_win32file.py 25 Jan 2009 03:21:55 -0000 1.27 --- test_win32file.py 25 Jan 2009 23:50:53 -0000 1.28 *************** *** 11,14 **** --- 11,15 ---- import socket import datetime + import random try: *************** *** 557,560 **** --- 558,674 ---- os.unlink(fname) + class TestConnect(unittest.TestCase): + def test_connect_with_payload(self): + def runner(): + s1 = socket.socket() + self.addr = ('localhost', random.randint(10000,64000)) + s1.bind(self.addr) + s1.listen(1) + cli, addr = s1.accept() + self.request = cli.recv(1024) + cli.send('some expected response') + t = threading.Thread(target=runner) + t.start() + time.sleep(0.1) + s2 = socket.socket() + ol = pywintypes.OVERLAPPED() + s2.bind(('0.0.0.0', 0)) # connectex requires the socket be bound beforehand + win32file.ConnectEx(s2, self.addr, ol, "some expected request") + win32file.GetOverlappedResult(s2.fileno(), ol, 1) + ol = pywintypes.OVERLAPPED() + buff = win32file.AllocateReadBuffer(1024) + win32file.WSARecv(s2, buff, ol, 0) + length = win32file.GetOverlappedResult(s2.fileno(), ol, 1) + self.response = buff[:length] + self.assertEqual(self.response, 'some expected response') + self.assertEqual(self.request, 'some expected request') + t.join(5) + self.failIf(t.isAlive(), "worker thread didn't terminate") + + def test_connect_without_payload(self): + def runner(): + s1 = socket.socket() + self.addr = ('localhost', random.randint(10000,64000)) + s1.bind(self.addr) + s1.listen(1) + cli, addr = s1.accept() + cli.send('some expected response') + t = threading.Thread(target=runner) + t.start() + time.sleep(0.1) + s2 = socket.socket() + ol = pywintypes.OVERLAPPED() + s2.bind(('0.0.0.0', 0)) # connectex requires the socket be bound beforehand + win32file.ConnectEx(s2, self.addr, ol) + win32file.GetOverlappedResult(s2.fileno(), ol, 1) + ol = pywintypes.OVERLAPPED() + buff = win32file.AllocateReadBuffer(1024) + win32file.WSARecv(s2, buff, ol, 0) + length = win32file.GetOverlappedResult(s2.fileno(), ol, 1) + self.response = buff[:length] + self.assertEqual(self.response, 'some expected response') + t.join(5) + self.failIf(t.isAlive(), "worker thread didn't terminate") + + class TestTransmit(unittest.TestCase): + def test_transmit(self): + import binascii + val = binascii.hexlify(os.urandom(1024*1024)) + val_length = len(val) + f = tempfile.TemporaryFile() + f.write(val) + + def runner(): + s1 = socket.socket() + self.addr = ('localhost', random.randint(10000,64000)) + s1.bind(self.addr) + s1.listen(1) + cli, addr = s1.accept() + buf = 1 + self.request = [] + while buf: + buf = cli.recv(1024*100) + self.request.append(buf) + + th = threading.Thread(target=runner) + th.start() + time.sleep(0.5) + s2 = socket.socket() + s2.connect(self.addr) + + length = 0 + + ol = pywintypes.OVERLAPPED() + f.seek(0) + win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0) + length += win32file.GetOverlappedResult(s2.fileno(), ol, 1) + + ol = pywintypes.OVERLAPPED() + f.seek(0) + win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0, "[AAA]", "[BBB]") + length += win32file.GetOverlappedResult(s2.fileno(), ol, 1) + + ol = pywintypes.OVERLAPPED() + f.seek(0) + win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0, "", "") + length += win32file.GetOverlappedResult(s2.fileno(), ol, 1) + + ol = pywintypes.OVERLAPPED() + f.seek(0) + win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0, None, "[CCC]") + length += win32file.GetOverlappedResult(s2.fileno(), ol, 1) + + ol = pywintypes.OVERLAPPED() + f.seek(0) + win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0, "[DDD]") + length += win32file.GetOverlappedResult(s2.fileno(), ol, 1) + + s2.close() + th.join() + buf = ''.join(self.request) + self.assertEqual(length, len(buf)) + self.assert_(("%s[AAA]%s[BBB]%s%s[CCC][DDD]%s" % (val,val,val,val,val)) == buf) + + if __name__ == '__main__': unittest.main() |
From: Mark H. <mha...@us...> - 2009-01-25 23:50:59
|
Update of /cvsroot/pywin32/pywin32/win32/src In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv32317/win32/src Modified Files: win32file.i Log Message: Merge win32file.ConnectEx and TransmitFile changes from [1962146], via Roger on the py3k branch. Index: win32file.i =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/win32file.i,v retrieving revision 1.97 retrieving revision 1.98 diff -C2 -d -r1.97 -r1.98 *** win32file.i 3 Jan 2009 06:43:58 -0000 1.97 --- win32file.i 25 Jan 2009 23:50:53 -0000 1.98 *************** *** 35,38 **** --- 35,44 ---- #include <stddef.h> #include "sfc.h" + + // pyconfig.h defines socklen_t, which conflicts with below header + #ifdef socklen_t + # undef socklen_t + #endif + #include "Ws2tcpip.h" #endif *************** *** 383,388 **** if (ret==NULL) return NULL; ! (*ret->ob_type->tp_as_buffer->bf_getwritebuffer)(ret, 0, &OutBuffer); ! bBuffer=TRUE; } else{ --- 389,396 ---- if (ret==NULL) return NULL; ! if (!PyWinObject_AsWriteBuffer(ret, &OutBuffer, &OutBufferSize)){ ! Py_DECREF(ret); ! return NULL; ! } } else{ *************** *** 435,439 **** if (bBuffer){ // Create a view of existing buffer with actual output size ! PyObject *resized=PyBuffer_FromReadWriteObject(ret, 0, numRead); Py_DECREF(ret); ret=resized; --- 443,452 ---- if (bBuffer){ // Create a view of existing buffer with actual output size ! // Memoryview object in py3k supports slicing ! #if (PY_VERSION_HEX >= 0x03000000) ! PyObject *resized=PySequence_GetSlice(ret, 0, numRead); ! #else ! PyObject *resized=PyBuffer_FromReadWriteObject(ret, 0, numRead); ! #endif Py_DECREF(ret); ret=resized; *************** *** 446,452 **** PyCFunction pfnpy_DeviceIoControl=(PyCFunction)py_DeviceIoControl; %} %native (OVERLAPPED) PyWinMethod_NewOVERLAPPED; ! %native(DeviceIoControl) pfnpy_DeviceIoControl; --- 459,467 ---- PyCFunction pfnpy_DeviceIoControl=(PyCFunction)py_DeviceIoControl; %} + %native(DeviceIoControl) pfnpy_DeviceIoControl; + %native (OVERLAPPED) PyWinMethod_NewOVERLAPPED; ! *************** *** 1629,1632 **** --- 1644,1832 ---- %} + + %{ + // @pyswig |TransmitFile|Transmits a file over a socket + // TransmitFile(sock, filehandle, bytes_to_write, bytes_per_send, overlap, flags [, (prepend_buf, postpend_buf)]) + // @rdesc Returns 0 on completion, or ERROR_IO_PENDING if an overlapped operation has been queued + static PyObject *py_TransmitFile( PyObject *self, PyObject *args, PyObject *kwargs ) { + PyObject *obhFile; + HANDLE hFile; + SOCKET s; + PyObject *obOverlapped = NULL; + PyObject *obSocket; + PyObject *obHead=Py_None, *obTail=Py_None; + DWORD flags, bytes_to_write, bytes_per_send; + OVERLAPPED *pOverlapped; + int error, rc; + + static char *keywords[]={"Socket","File","NumberOfBytesToWrite", "NumberOfBytesPerSend", + "Overlapped","Flags","Head","Tail", NULL}; + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OOiiOi|OO:TransmitFile", keywords, + &obSocket, // @pyparm <o PySocket>/int|Socket||Socket that will be used to send the file + &obhFile, // @pyparm <o PyHANDLE>/int|File||Handle to the file + &bytes_to_write, // @pyparm int|NumberOfBytesToWrite||The number of bytes in the file to transmit, use 0 for entire file. + &bytes_per_send, // @pyparm int|NumberOfBytesPerSend||The size, in bytes, of each block of data sent in each send operation. + &obOverlapped, // @pyparm <o PyOVERLAPPED>|Overlapped||An overlapped structure, can be None. + &flags, // @pyparm int|Flags||A set of flags used to modify the behavior of the TransmitFile function call. (win32file.TF_*) + &obHead, // @pyparm buffer|Head|None|Buffer to send on the socket before the file + &obTail)) // @pyparm buffer|Tail|None|Buffer to send on the socket after the file + return NULL; + + if (!PySocket_AsSOCKET(obSocket, &s)) { + return NULL; + } + GUID guid = WSAID_TRANSMITFILE; + DWORD dwBytes; + LPFN_TRANSMITFILE lpfnTransmitFile = NULL; + + error = WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(GUID), + &lpfnTransmitFile, sizeof(lpfnTransmitFile), &dwBytes, NULL, NULL); + if (error == SOCKET_ERROR) { + rc = WSAGetLastError(); + PyWin_SetAPIError("WSAIoctl", rc); + return NULL; + } + if (!PyWinObject_AsOVERLAPPED(obOverlapped, &pOverlapped, TRUE)) + return NULL; + if (!PyWinObject_AsHANDLE(obhFile, &hFile)) { + return NULL; + } + TRANSMIT_FILE_BUFFERS tf_buffers; + TRANSMIT_FILE_BUFFERS *ptf_buffers; + if (!PyWinObject_AsReadBuffer(obHead, &tf_buffers.Head, &tf_buffers.HeadLength, TRUE)) + return NULL; + if (!PyWinObject_AsReadBuffer(obTail, &tf_buffers.Tail, &tf_buffers.TailLength, TRUE)) + return NULL; + + if (tf_buffers.Head || tf_buffers.Tail) + ptf_buffers = &tf_buffers; + else + ptf_buffers = NULL; + + rc=0; + Py_BEGIN_ALLOW_THREADS; + if (!lpfnTransmitFile(s, hFile, bytes_to_write, bytes_per_send, pOverlapped, ptf_buffers, flags)) + rc = WSAGetLastError(); + Py_END_ALLOW_THREADS; + + if (rc == 0 || rc == ERROR_IO_PENDING || rc == WSA_IO_PENDING) + return PyInt_FromLong(rc); + return PyWin_SetAPIError("TransmitFile", rc); + } + PyCFunction pfnpy_TransmitFile=(PyCFunction)py_TransmitFile; + %} + %native(TransmitFile) pfnpy_TransmitFile; + + //////////////////////////////////////////////////////////////////////////////// + %{ + // @pyswig (int, int)|ConnectEx|Version of connect that uses Overlapped I/O + // ConnectEx(sock, (addr, port), buf, overlap) + // @rdesc Returns the completion code and number of bytes sent. + // The error code will be 0 for a completed operation, or ERROR_IO_PENDING for a pending overlapped operation. + static PyObject *py_ConnectEx( PyObject *self, PyObject *args, PyObject *kwargs ) { + OVERLAPPED *pOverlapped = NULL; + SOCKET sConnecting; + PyObject *obOverlapped = NULL; + PyObject *obConnecting = NULL; + PyObject *obBuf = Py_None; + PyObject *addro; + void *buffer=NULL; + DWORD buffer_len=0; + int rc, error; + DWORD sent=0; + static char *keywords[]={"s","name","Overlapped","SendBuffer", NULL}; + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OOO|O:ConnectEx", keywords, + &obConnecting, // @pyparm <o PySocket>/int|s||A bound, unconnected socket that will be used to connect + &addro, // @pyparm tuple|name||Address to connect to (host, port) + &obOverlapped, // @pyparm <o PyOVERLAPPED>|Overlapped||An overlapped structure + &obBuf)) // @pyparm buffer|SendBuffer|None|Buffer to send on the socket after connect + return NULL; + + if (!PySocket_AsSOCKET(obConnecting, &sConnecting)) { + return NULL; + } + if (!PyWinObject_AsReadBuffer(obBuf, &buffer, &buffer_len, TRUE)) + return NULL; + + GUID guid = WSAID_CONNECTEX; + DWORD dwBytes; + LPFN_CONNECTEX lpfnConnectEx = NULL; + + error = WSAIoctl(sConnecting, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(GUID), + &lpfnConnectEx, sizeof(lpfnConnectEx), &dwBytes, NULL, NULL); + if (error == SOCKET_ERROR) { + rc = WSAGetLastError(); + PyWin_SetAPIError("WSAIoctl", rc); + return NULL; + } + // convert the address + // + char pbuf[30]; + char *hptr, *pptr; + PyObject *hobj = NULL; + PyObject *pobj = (PyObject *)NULL; + PyObject *idna = NULL; + + struct addrinfo hints, *res; + if (!PyArg_ParseTuple(addro, "OO:getaddrinfo", &hobj, &pobj)) { + return NULL; + } + if (hobj == Py_None) { + hptr = NULL; + } else if (PyUnicode_Check(hobj)) { + idna = PyObject_CallMethod(hobj, "encode", "s", "idna"); + if (!idna) + return NULL; + hptr = PyString_AsString(idna); + } else if (PyString_Check(hobj)) { + hptr = PyString_AsString(hobj); + } else { + PyErr_SetString(PyExc_TypeError, + "getaddrinfo() argument 1 must be string or None"); + return NULL; + } + if (PyInt_Check(pobj)) { + PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj)); + pptr = pbuf; + } else if (PyString_Check(pobj)) { + pptr = PyString_AsString(pobj); + } else if (pobj == Py_None) { + pptr = (char *)NULL; + } else { + PyErr_SetString(PyExc_TypeError, "Int or String expected"); + return NULL; + } + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_TCP; + error = getaddrinfo(hptr, pptr, &hints, &res); + if (error) + { + PyWin_SetAPIError("getaddrinfo", WSAGetLastError()); + return NULL; + } + // done screwing with the address + + if (!PyWinObject_AsOVERLAPPED(obOverlapped, &pOverlapped)) + { + return NULL; + } + + rc=0; + Py_BEGIN_ALLOW_THREADS; + if (!lpfnConnectEx(sConnecting, res->ai_addr, res->ai_addrlen, buffer, buffer_len, &sent, pOverlapped)) + rc=WSAGetLastError(); + Py_END_ALLOW_THREADS; + if (rc==0 || rc == ERROR_IO_PENDING) + return Py_BuildValue("ii", rc, sent); + return PyWin_SetAPIError("ConnectEx", rc); + } + PyCFunction pfnpy_ConnectEx=(PyCFunction)py_ConnectEx; + %} + %native(ConnectEx) pfnpy_ConnectEx; + + //////////////////////////////////////////////////////////////////////////////// %native(AcceptEx) MyAcceptEx; *************** *** 5067,5070 **** --- 5267,5272 ---- ||(strcmp(pmd->ml_name, "GetFileInformationByHandleEx")==0) // not impl yet ||(strcmp(pmd->ml_name, "DeviceIoControl")==0) + ||(strcmp(pmd->ml_name, "TransmitFile")==0) + ||(strcmp(pmd->ml_name, "ConnectEx")==0) ) pmd->ml_flags = METH_VARARGS | METH_KEYWORDS; |
From: Mark H. <mha...@us...> - 2009-01-25 23:49:22
|
Update of /cvsroot/pywin32/pywin32/win32/src In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv32263/win32/src Modified Files: win32apimodule.cpp Log Message: Merge win32api.GetPwrCapabilities from py3k branch Index: win32apimodule.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/win32apimodule.cpp,v retrieving revision 1.95 retrieving revision 1.96 diff -C2 -d -r1.95 -r1.96 *** win32apimodule.cpp 25 Jan 2009 03:17:58 -0000 1.95 --- win32apimodule.cpp 25 Jan 2009 23:49:17 -0000 1.96 *************** *** 21,24 **** --- 21,25 ---- #define SECURITY_WIN32 // required by below #include "security.h" // for GetUserNameEx + #include "PowrProf.h" // Identical to PyW32_BEGIN_ALLOW_THREADS except no script "{" !!! *************** *** 6057,6060 **** --- 6058,6113 ---- } + PyObject *PyWinObject_FromBATTERY_REPORTING_SCALE(PBATTERY_REPORTING_SCALE pbrs) + { + return Py_BuildValue("{s:N, s:N}", + "Granularity", PyLong_FromUnsignedLong(pbrs->Granularity), + "Capacity", PyLong_FromUnsignedLong(pbrs->Capacity)); + } + + // @pymethod dict|win32api|GetPwrCapabilities|Retrieves system's power capabilities + // @pyseeapi GetPwrCapabilities + // @comm Requires Win2k or later. + // @rdesc Returns a dict representing a SYSTEM_POWER_CAPABILITIES struct + PyObject *PyGetPwrCapabilities(PyObject *self, PyObject *args) + { + SYSTEM_POWER_CAPABILITIES spc; + if (!GetPwrCapabilities(&spc)) + return PyWin_SetAPIError("GetPwrCapabilities"); + return Py_BuildValue( + "{s:N, s:N, s:N, s:N, s:N, s:N, s:N, s:N, s:N, s:N, s:N, s:N, s:N, s:N, s:N," + " s:N, s:N, s:N, s:O, s:N, s:O, s:N, s:N, s:O, s:N, s:N, s:N, s:N, s:N}", + "PowerButtonPresent", PyBool_FromLong(spc.PowerButtonPresent), + "SleepButtonPresent", PyBool_FromLong(spc.SleepButtonPresent), + "LidPresent", PyBool_FromLong(spc.LidPresent), + "SystemS1", PyBool_FromLong(spc.SystemS1), + "SystemS2", PyBool_FromLong(spc.SystemS2), + "SystemS3", PyBool_FromLong(spc.SystemS3), + "SystemS4", PyBool_FromLong(spc.SystemS4), + "SystemS5", PyBool_FromLong(spc.SystemS5), + "HiberFilePresent", PyBool_FromLong(spc.HiberFilePresent), + "FullWake", PyBool_FromLong(spc.FullWake), + "VideoDimPresent", PyBool_FromLong(spc.VideoDimPresent), + "ApmPresent", PyBool_FromLong(spc.ApmPresent), + "UpsPresent", PyBool_FromLong(spc.UpsPresent), + "ThermalControl", PyBool_FromLong(spc.ThermalControl), + "ProcessorThrottle", PyBool_FromLong(spc.ProcessorThrottle), + "ProcessorMinThrottle", PyInt_FromLong(spc.ProcessorMinThrottle), + "ProcessorMaxThrottle", PyInt_FromLong(spc.ProcessorMaxThrottle), + "FastSystemS4", PyBool_FromLong(spc.FastSystemS4), + "spare2", Py_None, // reserved + "DiskSpinDown", PyBool_FromLong(spc.DiskSpinDown), + "spare3", Py_None, // reserved + "SystemBatteriesPresent", PyBool_FromLong(spc.SystemBatteriesPresent), + "BatteriesAreShortTerm", PyBool_FromLong(spc.BatteriesAreShortTerm), + "BatteryScale", Py_BuildValue("NNN", + PyWinObject_FromBATTERY_REPORTING_SCALE(&spc.BatteryScale[0]), + PyWinObject_FromBATTERY_REPORTING_SCALE(&spc.BatteryScale[1]), + PyWinObject_FromBATTERY_REPORTING_SCALE(&spc.BatteryScale[2])), + "AcOnLineWake", PyInt_FromLong(spc.AcOnLineWake), + "SoftLidWake", PyInt_FromLong(spc.SoftLidWake), + "RtcWake", PyInt_FromLong(spc.RtcWake), + "MinDeviceWakeState", PyInt_FromLong(spc.MinDeviceWakeState), + "DefaultLowLatencyWake", PyInt_FromLong(spc.DefaultLowLatencyWake)); + } /* List of functions exported by this module */ *************** *** 6156,6159 **** --- 6209,6213 ---- {"GetModuleFileNameW", PyGetModuleFileNameW,1}, // @pymeth GetModuleFileNameW|Retrieves the unicode filename of the specified module. {"GetModuleHandle", PyGetModuleHandle,1}, // @pymeth GetModuleHandle|Returns the handle of an already loaded DLL. + {"GetPwrCapabilities", PyGetPwrCapabilities, METH_NOARGS}, // @pymeth GetPwrCapabilities|Retrieves system's power capabilities {"GetProfileSection", PyGetProfileSection,1}, // @pymeth GetProfileSection|Returns a list of entries in an INI file. {"GetProcAddress", PyGetProcAddress,1}, // @pymeth GetProcAddress|Returns the address of the specified exported dynamic-link library (DLL) function. |
From: Mark H. <mha...@us...> - 2009-01-25 23:49:22
|
Update of /cvsroot/pywin32/pywin32 In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv32263 Modified Files: setup.py Log Message: Merge win32api.GetPwrCapabilities from py3k branch Index: setup.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/setup.py,v retrieving revision 1.93 retrieving revision 1.94 diff -C2 -d -r1.93 -r1.94 *** setup.py 25 Jan 2009 03:08:09 -0000 1.93 --- setup.py 25 Jan 2009 23:49:17 -0000 1.94 *************** *** 263,266 **** --- 263,267 ---- unicode_mode=None, # 'none'==default or specifically true/false. implib_name=None, + delay_load_libraries="", ): assert dsp_file or sources, "Either dsp_file or sources must be specified" *************** *** 269,272 **** --- 270,275 ---- 'win32/src'] + include_dirs libraries=libraries.split() + self.delay_load_libraries=delay_load_libraries.split() + libraries.extend(self.delay_load_libraries) if export_symbol_file: *************** *** 397,400 **** --- 400,408 ---- self.extra_compile_args.append("/EHsc") + if self.delay_load_libraries: + self.libraries.append("delayimp") + for delay_lib in self.delay_load_libraries: + self.extra_link_args.append("/delayload:%s.lib" % delay_lib) + # If someone needs a specially named implib created, handle that if self.implib_name: *************** *** 1358,1362 **** ("timer", "user32", None), ("win2kras", "rasapi32", None, 0x0500), - ("win32api", "user32 advapi32 shell32 version", None, 0x0500, 'win32/src/win32apimodule.cpp win32/src/win32api_display.cpp'), ("win32cred", "AdvAPI32 credui", True, 0x0501, 'win32/src/win32credmodule.cpp'), ("win32crypt", "Crypt32", None, 0x0500, 'win32/src/win32crypt.i'), --- 1366,1369 ---- *************** *** 1417,1420 **** --- 1424,1435 ---- # The few that need slightly special treatment win32_extensions += [ + WinExt_win32("win32api", + sources = """ + win32/src/win32apimodule.cpp win32/src/win32api_display.cpp + """.split(), + libraries="user32 advapi32 shell32 version", + delay_load_libraries="powrprof", + windows_h_version=0x0500, + ), WinExt_win32("win32gui", sources = """ |
From: Jason R. C. <ja...@us...> - 2009-01-25 14:47:03
|
Update of /cvsroot/pywin32/pywin32/win32/Lib In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv8391 Modified Files: win32timezone.py Log Message: Merged py3k fixes by Mark Hammond Merged ctypes-free Structures Index: win32timezone.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/Lib/win32timezone.py,v retrieving revision 1.24 retrieving revision 1.25 diff -C2 -d -r1.24 -r1.25 *** win32timezone.py 25 Jan 2009 03:30:04 -0000 1.24 --- win32timezone.py 25 Jan 2009 14:46:56 -0000 1.25 *************** *** 59,68 **** >>> est = win32timezone.TimeZoneInfo('Eastern Standard Time') ! >>> est.displayName ! u'(GMT-05:00) Eastern Time (US & Canada)' >>> gmt = win32timezone.TimeZoneInfo('GMT Standard Time', True) ! >>> gmt.displayName ! u'(GMT) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London' To get the complete list of available time zone keys, --- 59,68 ---- >>> est = win32timezone.TimeZoneInfo('Eastern Standard Time') ! >>> str(est.displayName) ! '(GMT-05:00) Eastern Time (US & Canada)' >>> gmt = win32timezone.TimeZoneInfo('GMT Standard Time', True) ! >>> str(gmt.displayName) ! '(GMT) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London' To get the complete list of available time zone keys, *************** *** 129,135 **** >>> isinstance(caps, dict) True ! >>> caps.has_key('MissingTZPatch') True ! >>> caps.has_key('DynamicTZSupport') True --- 129,135 ---- >>> isinstance(caps, dict) True ! >>> 'MissingTZPatch' in caps True ! >>> 'DynamicTZSupport' in caps True *************** *** 159,164 **** import datetime import win32api - import ctypes - import ctypes.wintypes import re import sys --- 159,162 ---- *************** *** 171,264 **** log = logging.getLogger(__file__) ! # define a constructor to enable Extended structure pickling ! def __construct_structure__(type_, buffer): ! "Construct a ctypes.Structure subclass from a buffer" ! assert issubclass(type_, ctypes.Structure) ! obj = type_.__new__(type_) ! # TODO, what if buffer is larger that the sizeof obj? ! ctypes.memmove(ctypes.addressof(obj), buffer, len(buffer)) ! return obj - class Extended(object): - "Used to add extended capability to structures" def __eq__(self, other): ! return str(buffer(self)) == str(buffer(other)) ! def __ne__(self, other): ! return str(buffer(self)) != str(buffer(other)) ! # this method wouldn't be necessary in ctypes 1.1 except ! # for the bug described http://bugs.python.org/issue5049 ! def __reduce__(self): ! """ ! A method to make ctypes.Structures pickleable ! from http://osdir.com/ml/python.ctypes/2006-03/msg00009.html ! """ ! args = (self.__class__, str(buffer(self))) ! return (globals()['__construct_structure__'], args) ! ! # A couple of C-type structures for working with the Windows Platform SDK ! class SYSTEMTIME(Extended, ctypes.Structure): _fields_ = [ ! ('year', ctypes.c_ushort), ! ('month', ctypes.c_ushort), ! ('day_of_week', ctypes.c_ushort), ! ('day', ctypes.c_ushort), ! ('hour', ctypes.c_ushort), ! ('minute', ctypes.c_ushort), ! ('second', ctypes.c_ushort), ! ('millisecond', ctypes.c_ushort), ] ! class TIME_ZONE_INFORMATION(Extended, ctypes.Structure): _fields_ = [ ! ('bias', ctypes.c_long), ! ('standard_name', ctypes.c_wchar*32), ('standard_start', SYSTEMTIME), ! ('standard_bias', ctypes.c_long), ! ('daylight_name', ctypes.c_wchar*32), ('daylight_start', SYSTEMTIME), ! ('daylight_bias', ctypes.c_long), ] ! class DYNAMIC_TIME_ZONE_INFORMATION(TIME_ZONE_INFORMATION): ! """ ! Because the structure of the DYNAMIC_TIME_ZONE_INFORMATION extends ! the structure of the TIME_ZONE_INFORMATION, this structure ! can be used as a drop-in replacement for calls where the ! structure is passed by reference. ! ! For example, ! dynamic_tzi = DYNAMIC_TIME_ZONE_INFORMATION() ! ctypes.windll.kernel32.GetTimeZoneInformation(ctypes.byref(dynamic_tzi)) ! ! (although the key_name and dynamic_daylight_time_disabled flags will be ! set to the default (null)). ! ! >>> isinstance(DYNAMIC_TIME_ZONE_INFORMATION(), TIME_ZONE_INFORMATION) ! True ! ! ! """ ! _fields_ = [ ! # ctypes automatically includes the fields from the parent ! ('key_name', ctypes.c_wchar*128), ! ('dynamic_daylight_time_disabled', ctypes.wintypes.BOOL), ] - - def __init__(self, *args, **kwargs): - """Allow initialization from args from both this class and - its superclass. Default ctypes implementation seems to - assume that this class is only initialized with its own - _fields_ (for non-keyword-args).""" - super_self = super(DYNAMIC_TIME_ZONE_INFORMATION, self) - super_fields = super_self._fields_ - super_args = args[:len(super_fields)] - self_args = args[len(super_fields):] - # convert the super args to keyword args so they're also handled - for field, arg in zip(super_fields, super_args): - field_name, spec = field - kwargs[field_name] = arg - super(DYNAMIC_TIME_ZONE_INFORMATION, self).__init__(*self_args, **kwargs) --- 169,240 ---- log = logging.getLogger(__file__) ! # A couple of objects for working with objects as if they were native C-type ! # structures. ! class _SimpleStruct(object): ! _fields_ = None # must be overridden by subclasses ! def __init__(self, *args, **kw): ! for i, (name, typ) in enumerate(self._fields_): ! def_arg = None ! if i < len(args): ! def_arg = args[i] ! if name in kw: ! def_arg = kw[name] ! if def_arg is not None: ! if not isinstance(def_arg, tuple): ! def_arg = (def_arg,) ! else: ! def_arg = () ! if len(def_arg)==1 and isinstance(def_arg[0], typ): ! # already an object of this type. ! # XXX - should copy.copy??? ! def_val = def_arg[0] ! else: ! def_val = typ(*def_arg) ! setattr(self, name, def_val) ! ! def field_names(self): ! return [f[0] for f in fields] def __eq__(self, other): ! if not hasattr(other, "_fields_"): ! return False ! if self._fields_ != other._fields_: ! return False ! for name, _ in self._fields_: ! if getattr(self, name) != getattr(other, name): ! return False ! return True ! def __ne__(self, other): ! return not self.__eq__(other) ! class SYSTEMTIME(_SimpleStruct): _fields_ = [ ! ('year', int), ! ('month', int), ! ('day_of_week', int), ! ('day', int), ! ('hour', int), ! ('minute', int), ! ('second', int), ! ('millisecond', int), ] ! class TIME_ZONE_INFORMATION(_SimpleStruct): _fields_ = [ ! ('bias', int), ! ('standard_name', str), ('standard_start', SYSTEMTIME), ! ('standard_bias', int), ! ('daylight_name', str), ('daylight_start', SYSTEMTIME), ! ('daylight_bias', int), ] ! class DYNAMIC_TIME_ZONE_INFORMATION(_SimpleStruct): ! _fields_ = TIME_ZONE_INFORMATION._fields_ + [ ! ('key_name', str), ! ('dynamic_daylight_time_disabled', bool), ] *************** *** 272,278 **** """ - def field_names(self): - return map(operator.itemgetter(0), self._fields_) - def __init__(self, *args, **kwargs): """ --- 248,251 ---- *************** *** 285,291 **** super(TimeZoneDefinition, self).__init__(*args, **kwargs) return ! except TypeError: pass ! try: self.__init_from_other(*args, **kwargs) --- 258,264 ---- super(TimeZoneDefinition, self).__init__(*args, **kwargs) return ! except (TypeError, ValueError): pass ! try: self.__init_from_other(*args, **kwargs) *************** *** 326,331 **** def __getattribute__(self, attr): value = super(TimeZoneDefinition, self).__getattribute__(attr) - make_minute_timedelta = lambda m: datetime.timedelta(minutes = m) if 'bias' in attr: value = make_minute_timedelta(value) return value --- 299,304 ---- def __getattribute__(self, attr): value = super(TimeZoneDefinition, self).__getattribute__(attr) if 'bias' in attr: + make_minute_timedelta = lambda m: datetime.timedelta(minutes = m) value = make_minute_timedelta(value) return value *************** *** 334,351 **** def current(class_): "Windows Platform SDK GetTimeZoneInformation" ! tzi = class_() ! kernel32 = ctypes.windll.kernel32 ! getter = kernel32.GetTimeZoneInformation ! getter = getattr(kernel32, 'GetDynamicTimeZoneInformation', getter) ! code = getter(ctypes.byref(tzi)) ! return code, tzi def set(self): ! kernel32 = ctypes.windll.kernel32 ! setter = kernel32.SetTimeZoneInformation ! setter = getattr(kernel32, 'SetDynamicTimeZoneInformation', setter) ! return setter(ctypes.byref(self)) def copy(self): return self.__class__(self) --- 307,319 ---- def current(class_): "Windows Platform SDK GetTimeZoneInformation" ! code, tzi = win32api.GetTimeZoneInformation(True) ! return code, class_(*tzi) def set(self): ! tzi = tuple(getattr(self, n) for n, t in self._fields_) ! win32api.SetTimeZoneInformation(tzi) def copy(self): + # XXX - this is no longer a copy! return self.__class__(self) *************** *** 409,413 **** # this key works for WinNT+, but not for the Win95 line. tzRegKey = r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones' ! def __init__(self, param=None, fix_standard_time=False): if isinstance(param, TimeZoneDefinition): --- 377,381 ---- # this key works for WinNT+, but not for the Win95 line. tzRegKey = r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones' ! def __init__(self, param=None, fix_standard_time=False): if isinstance(param, TimeZoneDefinition): *************** *** 544,547 **** --- 512,521 ---- return cmp(self.__dict__, other.__dict__) + def __eq__(self, other): + return self.__dict__==other.__dict__ + + def __ne__(self, other): + return self.__dict__!=other.__dict__ + @classmethod def local(class_): *************** *** 604,608 **** Get the names of the registry keys indexed by a value in that key. """ ! key_names = TimeZoneInfo._get_time_zone_key_names() def get_index_value(key_name): key = TimeZoneInfo._get_time_zone_key(key_name) --- 578,582 ---- Get the names of the registry keys indexed by a value in that key. """ ! key_names = list(TimeZoneInfo._get_time_zone_key_names()) def get_index_value(key_name): key = TimeZoneInfo._get_time_zone_key(key_name) *************** *** 616,624 **** tzs = TimeZoneInfo.get_sorted_time_zones() get_standard_name = lambda tzi: tzi.standardName ! return map(get_standard_name, tzs) @staticmethod def get_all_time_zones(): ! return map(TimeZoneInfo, TimeZoneInfo._get_time_zone_key_names()) @staticmethod --- 590,598 ---- tzs = TimeZoneInfo.get_sorted_time_zones() get_standard_name = lambda tzi: tzi.standardName ! return [get_standard_name(tz) for tz in tzs] @staticmethod def get_all_time_zones(): ! return [TimeZoneInfo(n) for n in TimeZoneInfo._get_time_zone_key_names()] @staticmethod *************** *** 650,655 **** def __load_values(self): ! get_name_value = lambda (name, value, type): (name, value) ! pairs = map(get_name_value, self._enumerate_reg_values(self.key)) self.update(pairs) --- 624,628 ---- def __load_values(self): ! pairs = [(n, v) for (n, v, t) in self._enumerate_reg_values(self.key)] self.update(pairs) *************** *** 711,740 **** return datetime.datetime.now(TimeZoneInfo.local()) - # A timezone info for utc - pywintypes uses a single instance of this class - # to return SYSTEMTIME instances. - class TimeZoneUTC(TimeZoneInfo): - """A UTC Time Zone instance that initializes statically (without - accessing the registry or apis). - """ - def __new__(cls): - # no need to make more than one of these - try: - return cls._instance - except AttributeError: - cls._instance = cls.__create_instance() - return cls._instance - - def __init__(self): - pass - - @classmethod - def __create_instance(cls): - tzi = TimeZoneDefinition(standardname='Universal Coordinated Time') - cls._instance = TimeZoneInfo.__new__(cls, tzi) - - - def __repr__(self): - return "%s()" % self.__class__.__name__ - def GetTZCapabilities(): """Run a few known tests to determine the capabilities of the time zone database --- 684,687 ---- *************** *** 761,764 **** --- 708,715 ---- def resolveMUITimeZone(spec): """Resolve a multilingual user interface resource for the time zone name + >>> #some pre-amble for the doc-tests to be py2k and py3k aware) + >>> try: unicode and None + ... except NameError: unicode=str + ... >>> result = resolveMUITimeZone('@tzres.dll,-110') >>> expectedResultType = [type(None),unicode][sys.getwindowsversion() >= (6,)] *************** *** 829,835 **** self.match = keyMatchComparator ! def __getitem__(self, item): sortedKeys = self.keys() ! sortedKeys.sort(self.sort) if isinstance(item, RangeItem): result = self.__getitem__(sortedKeys[item]) --- 780,791 ---- self.match = keyMatchComparator ! def _get_sorted_keys(self): sortedKeys = self.keys() ! reverse = self.match != operator.le ! sortedKeys.sort(reverse=reverse) ! return sortedKeys ! ! def __getitem__(self, item): ! sortedKeys = self._get_sorted_keys() if isinstance(item, RangeItem): result = self.__getitem__(sortedKeys[item]) *************** *** 843,847 **** is_match = lambda k: self.match(item, k) # use of ifilter here would be more efficent ! matches = filter(is_match, keys) if matches: return matches[0] --- 799,803 ---- is_match = lambda k: self.match(item, k) # use of ifilter here would be more efficent ! matches = [k for k in keys if is_match(k)] if matches: return matches[0] *************** *** 849,854 **** def bounds(self): ! sortedKeys = self.keys() ! sortedKeys.sort(self.sort) return sortedKeys[RangeItemFirst()], sortedKeys[RangeItemLast()] --- 805,809 ---- def bounds(self): ! sortedKeys = self._get_sorted_keys() return sortedKeys[RangeItemFirst()], sortedKeys[RangeItemLast()] |
From: Mark H. <mha...@us...> - 2009-01-25 05:04:13
|
Update of /cvsroot/pywin32/pywin32/win32/Lib In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv25570 Modified Files: pywintypes.py Log Message: have the system loader work on py3k and document/assert how things work on both versions Index: pywintypes.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/Lib/pywintypes.py,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** pywintypes.py 14 Nov 2008 00:22:25 -0000 1.14 --- pywintypes.py 25 Jan 2009 05:04:07 -0000 1.15 *************** *** 1,5 **** # Magic utility that "redirects" to pywintypesxx.dll import imp, sys, os - sys.modules['pywintypes_loader']=sys.modules['pywintypes'] def __import_pywin32_system_module__(modname, globs): # This has been through a number of iterations. The problem: how to --- 1,4 ---- *************** *** 32,35 **** --- 31,36 ---- (ext, mode, ext_type)) # and fill our namespace with it. + # XXX - if this ever moves to py3k, this will probably + # need similar adjustments as below... globs.update(mod.__dict__) return *************** *** 96,104 **** # give up in disgust. raise ImportError("No system module '%s' (%s)" % (modname, filename)) # Python can load the module ! mod = imp.load_module(modname, None, found, ! ('.dll', 'rb', imp.C_EXTENSION)) ! # and fill our namespace with it. ! globs.update(mod.__dict__) __import_pywin32_system_module__("pywintypes", globals()) --- 97,124 ---- # give up in disgust. raise ImportError("No system module '%s' (%s)" % (modname, filename)) + # py2k and py3k differences: + # On py2k, after doing "imp.load_module('pywintypes')", sys.modules + # is unchanged - ie, sys.modules['pywintypes'] still refers to *this* + # .py module - but the module's __dict__ has *already* need updated + # with the new module's contents. + # However, on py3k, sys.modules *is* changed - sys.modules['pywintypes'] + # will be changed to the new module object. + # SO: * on py2k don't need to update any globals. + # * on py3k we update our module dict with the new module's dict and + # copy its globals to ours. + old_mod = sys.modules[modname] # Python can load the module ! mod = imp.load_dynamic(modname, found) ! # Check the sys.modules[] behaviour we describe above is true... ! if sys.version_info < (3,0): ! assert sys.modules[modname] is old_mod ! assert mod is old_mod ! else: ! assert sys.modules[modname] is not old_mod ! assert sys.modules[modname] is mod ! # as above - re-reset to the *old* module object then update globs. ! sys.modules[modname] = old_mod ! globs.update(mod.__dict__) ! __import_pywin32_system_module__("pywintypes", globals()) |
From: Mark H. <mha...@us...> - 2009-01-25 04:52:36
|
Update of /cvsroot/pywin32/pywin32/win32/Lib In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv24579/win32/Lib Modified Files: Tag: py3k pywin32_testutil.py Log Message: merge recent changes from the trunk Index: pywin32_testutil.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/Lib/pywin32_testutil.py,v retrieving revision 1.1.2.2 retrieving revision 1.1.2.3 diff -C2 -d -r1.1.2.2 -r1.1.2.3 *** pywin32_testutil.py 7 Jan 2009 06:25:16 -0000 1.1.2.2 --- pywin32_testutil.py 25 Jan 2009 04:52:20 -0000 1.1.2.3 *************** *** 9,12 **** --- 9,16 ---- ## + def int2long(val): + """return a long on py2k""" + return val + 0x100000000 - 0x100000000 + # The test suite has lots of string constants containing binary data, but # the strings are used in various "bytes" contexts. *************** *** 82,86 **** msg = "%d interface objects and %d gateway objects leaked" \ % (lost_i, lost_g) ! result.addFailure(self.real_test, (AssertionError, msg, None)) def runTest(self): --- 86,91 ---- msg = "%d interface objects and %d gateway objects leaked" \ % (lost_i, lost_g) ! exc = AssertionError(msg) ! result.addFailure(self.real_test, (exc.__class__, exc, None)) def runTest(self): *************** *** 109,113 **** if lost > 0: msg = "LeakTest: %s lost %d references" % (self.real_test, lost) ! result.addFailure(self.real_test, (AssertionError, msg, None)) --- 114,119 ---- if lost > 0: msg = "LeakTest: %s lost %d references" % (self.real_test, lost) ! exc = AssertionError(msg) ! result.addFailure(self.real_test, (exc.__class__, exc, None)) |
From: Mark H. <mha...@us...> - 2009-01-25 04:52:32
|
Update of /cvsroot/pywin32/pywin32/com/win32com/src In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv24579/com/win32com/src Modified Files: Tag: py3k oleargs.cpp Log Message: merge recent changes from the trunk Index: oleargs.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/src/oleargs.cpp,v retrieving revision 1.41.2.7 retrieving revision 1.41.2.8 diff -C2 -d -r1.41.2.7 -r1.41.2.8 *** oleargs.cpp 14 Jan 2009 12:42:02 -0000 1.41.2.7 --- oleargs.cpp 25 Jan 2009 04:52:20 -0000 1.41.2.8 *************** *** 48,52 **** BOOL bGoodEmpty = FALSE; // Set if VT_EMPTY should really be used. V_VT(var) = VT_EMPTY; ! if ( PyString_Check(obj) || PyUnicode_Check(obj) ) { if ( !PyWinObject_AsBstr(obj, &V_BSTR(var)) ) { --- 48,57 ---- BOOL bGoodEmpty = FALSE; // Set if VT_EMPTY should really be used. V_VT(var) = VT_EMPTY; ! if ( ! // In py3k we don't convert PyString_Check objects (ie, bytes) to BSTR... ! #if (PY_VERSION_HEX < 0x03000000) ! PyString_Check(obj) || ! #endif ! PyUnicode_Check(obj) ) { if ( !PyWinObject_AsBstr(obj, &V_BSTR(var)) ) { |
From: Mark H. <mha...@us...> - 2009-01-25 04:52:32
|
Update of /cvsroot/pywin32/pywin32/com/win32com/src/extensions In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv24579/com/win32com/src/extensions Modified Files: Tag: py3k PyIType.cpp Log Message: merge recent changes from the trunk Index: PyIType.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/src/extensions/PyIType.cpp,v retrieving revision 1.9.4.2 retrieving revision 1.9.4.3 diff -C2 -d -r1.9.4.2 -r1.9.4.3 *** PyIType.cpp 26 Nov 2008 07:17:39 -0000 1.9.4.2 --- PyIType.cpp 25 Jan 2009 04:52:20 -0000 1.9.4.3 *************** *** 44,48 **** --- 44,50 ---- ITypeLib *ptlib; unsigned index; + PY_INTERFACE_PRECALL; SCODE sc = pMyTypeInfo->GetContainingTypeLib(&ptlib, &index); + PY_INTERFACE_POSTCALL; if (FAILED(sc)) return PyCom_BuildPyException(sc, pMyTypeInfo, IID_ITypeInfo); |
From: Mark H. <mha...@us...> - 2009-01-25 04:52:32
|
Update of /cvsroot/pywin32/pywin32/com/win32comext/directsound/test In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv24579/com/win32comext/directsound/test Added Files: Tag: py3k __init__.py Log Message: merge recent changes from the trunk --- NEW FILE: __init__.py --- # This is a Python package, imported by the win32com test suite. |
Update of /cvsroot/pywin32/pywin32/win32/test In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv24579/win32/test Modified Files: Tag: py3k handles.py test_odbc.py test_pywintypes.py test_win32event.py test_win32trace.py Log Message: merge recent changes from the trunk Index: test_pywintypes.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_pywintypes.py,v retrieving revision 1.3.4.4 retrieving revision 1.3.4.5 diff -C2 -d -r1.3.4.4 -r1.3.4.5 *** test_pywintypes.py 8 Jan 2009 03:45:50 -0000 1.3.4.4 --- test_pywintypes.py 25 Jan 2009 04:52:20 -0000 1.3.4.5 *************** *** 10,14 **** pytime_current = pywintypes.Time(struct_current) # try and test all the standard parts of the format ! format_strings = "%a %A %b %B %c %d %H %I %j %m %M %p %S %U %w %W %x %X %y %Y %Z" for fmt in format_strings.split(): v1 = pytime_current.Format(fmt) --- 10,16 ---- pytime_current = pywintypes.Time(struct_current) # try and test all the standard parts of the format ! # Note we used to include '%Z' testing, but that was pretty useless as ! # it always returned the local timezone. ! format_strings = "%a %A %b %B %c %d %H %I %j %m %M %p %S %U %w %W %x %X %y %Y" for fmt in format_strings.split(): v1 = pytime_current.Format(fmt) Index: test_odbc.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_odbc.py,v retrieving revision 1.7.2.4 retrieving revision 1.7.2.5 diff -C2 -d -r1.7.2.4 -r1.7.2.5 *** test_odbc.py 7 Jan 2009 06:25:16 -0000 1.7.2.4 --- test_odbc.py 25 Jan 2009 04:52:20 -0000 1.7.2.5 *************** *** 130,134 **** self._test_val('intfield', 1) self._test_val('intfield', 0) ! self._test_val('intfield', sys.maxsize) def testFloat(self): --- 130,138 ---- self._test_val('intfield', 1) self._test_val('intfield', 0) ! try: ! big = sys.maxsize ! except AttributeError: ! big = sys.maxint ! self._test_val('intfield', big) def testFloat(self): Index: test_win32trace.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_win32trace.py,v retrieving revision 1.5.4.2 retrieving revision 1.5.4.3 diff -C2 -d -r1.5.4.2 -r1.5.4.3 *** test_win32trace.py 4 Dec 2008 07:28:46 -0000 1.5.4.2 --- test_win32trace.py 25 Jan 2009 04:52:20 -0000 1.5.4.3 *************** *** 15,19 **** time.sleep(0.05) if win32trace.read() != "Hi": ! # Reset everything so following tests still fail with this error!S win32trace.TermRead() win32trace.TermWrite() --- 15,19 ---- time.sleep(0.05) if win32trace.read() != "Hi": ! # Reset everything so following tests still fail with this error! win32trace.TermRead() win32trace.TermWrite() *************** *** 102,109 **** --- 102,122 ---- self.assertEquals('Syver Enstad', syverEnstad) + def testRoundTripUnicode(self): + win32trace.write('\xa9opyright Syver Enstad') + syverEnstad = win32trace.read() + # str objects are always returned in py2k (latin-1 encoding was used + # on unicode objects) + self.assertEquals('\xa9opyright Syver Enstad', syverEnstad) + def testBlockingRead(self): win32trace.write('Syver Enstad') self.assertEquals('Syver Enstad', win32trace.blockingread()) + def testBlockingReadUnicode(self): + win32trace.write('\xa9opyright Syver Enstad') + # str objects are always returned in py2k (latin-1 encoding was used + # on unicode objects) + self.assertEquals('\xa9opyright Syver Enstad', win32trace.blockingread()) + def testFlush(self): win32trace.flush() Index: test_win32event.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_win32event.py,v retrieving revision 1.1.4.2 retrieving revision 1.1.4.3 diff -C2 -d -r1.1.4.2 -r1.1.4.3 *** test_win32event.py 27 Nov 2008 11:31:11 -0000 1.1.4.2 --- test_win32event.py 25 Jan 2009 04:52:20 -0000 1.1.4.3 *************** *** 4,9 **** --- 4,17 ---- import os import sys + from pywin32_testutil import int2long class TestWaitableTimer(unittest.TestCase): + def testWaitableFireLong(self): + h = win32event.CreateWaitableTimer(None, 0, None) + dt = int2long(-160) # 160 ns. + win32event.SetWaitableTimer(h, dt, 0, None, None, 0) + rc = win32event.WaitForSingleObject(h, 1000) + self.failUnlessEqual(rc, win32event.WAIT_OBJECT_0) + def testWaitableFire(self): h = win32event.CreateWaitableTimer(None, 0, None) Index: handles.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/handles.py,v retrieving revision 1.4.2.3 retrieving revision 1.4.2.4 diff -C2 -d -r1.4.2.3 -r1.4.2.4 *** handles.py 11 Dec 2008 04:13:36 -0000 1.4.2.3 --- handles.py 25 Jan 2009 04:52:20 -0000 1.4.2.4 *************** *** 3,6 **** --- 3,7 ---- import pywintypes import win32api + from pywin32_testutil import int2long # A class that will never die vie refcounting, but will die via GC. *************** *** 108,112 **** self.assertRaises(TypeError, pywintypes.HANDLE, ()) # should be able to get a long! ! pywintypes.HANDLE(0) if __name__ == '__main__': --- 109,113 ---- self.assertRaises(TypeError, pywintypes.HANDLE, ()) # should be able to get a long! ! pywintypes.HANDLE(int2long(0)) if __name__ == '__main__': |
From: Mark H. <mha...@us...> - 2009-01-25 04:52:31
|
Update of /cvsroot/pywin32/pywin32 In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv24579 Modified Files: Tag: py3k setup.py Log Message: merge recent changes from the trunk Index: setup.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/setup.py,v retrieving revision 1.81.2.14 retrieving revision 1.81.2.15 diff -C2 -d -r1.81.2.14 -r1.81.2.15 *** setup.py 14 Jan 2009 12:42:02 -0000 1.81.2.14 --- setup.py 25 Jan 2009 04:52:19 -0000 1.81.2.15 *************** *** 403,407 **** if self.implib_name: implib = os.path.join(build_ext.build_temp, self.implib_name) ! self.extra_link_args.append("/IMPLIB:%s" % implib) # Try and find the MFC source code, so we can reach inside for # some of the ActiveX support we need. We need to do this late, so --- 403,411 ---- if self.implib_name: implib = os.path.join(build_ext.build_temp, self.implib_name) ! if build_ext.debug: ! suffix = "_d" ! else: ! suffix = "" ! self.extra_link_args.append("/IMPLIB:%s%s.lib" % (implib, suffix)) # Try and find the MFC source code, so we can reach inside for # some of the ActiveX support we need. We need to do this late, so *************** *** 1605,1609 **** dsp_file=r"com\Active Scripting.dsp", extra_compile_args = ['-DPY_BUILD_AXSCRIPT'], ! implib_name="axscript.lib", pch_header = "stdafx.h" ), --- 1609,1613 ---- dsp_file=r"com\Active Scripting.dsp", extra_compile_args = ['-DPY_BUILD_AXSCRIPT'], ! implib_name="axscript", pch_header = "stdafx.h" ), *************** *** 1750,1754 **** %(propsys)s/propsys.cpp """ % dirs).split(), ! implib_name="pypropsys.lib", ), --- 1754,1758 ---- %(propsys)s/propsys.cpp """ % dirs).split(), ! implib_name="pypropsys", ), |
From: Mark H. <mha...@us...> - 2009-01-25 04:52:31
|
Update of /cvsroot/pywin32/pywin32/Pythonwin/pywin/tools In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv24579/Pythonwin/pywin/tools Modified Files: Tag: py3k browser.py Log Message: merge recent changes from the trunk Index: browser.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/Pythonwin/pywin/tools/browser.py,v retrieving revision 1.10.2.7 retrieving revision 1.10.2.8 diff -C2 -d -r1.10.2.7 -r1.10.2.8 *** browser.py 14 Jan 2009 12:42:02 -0000 1.10.2.7 --- browser.py 25 Jan 2009 04:52:20 -0000 1.10.2.8 *************** *** 6,9 **** --- 6,11 ---- # or # >>> browser.Browse(your_module) + import sys + import types import __main__ import win32ui *************** *** 11,15 **** from . import hierlist - from types import * special_names = [ '__doc__', '__name__', '__self__' ] --- 13,16 ---- *************** *** 265,286 **** TypeMap = { type : HLIClass, ! FunctionType: HLIFunction, tuple: HLITuple, dict: HLIDict, list: HLIList, ! ModuleType: HLIModule, ! CodeType : HLICode, ! BuiltinFunctionType : HLIBuiltinFunction, ! FrameType : HLIFrame, ! TracebackType : HLITraceback, str : HLIString, int: HLIPythonObject, ! ## LongType: HLIPythonObject, - hrm - fixme for py2k float: HLIPythonObject, } - try: - TypeMap[UnicodeType] = HLIString - except NameError: - pass # Python 1.5 - no Unicode - no problem! def MakeHLI( ob, name=None ): --- 266,285 ---- TypeMap = { type : HLIClass, ! types.FunctionType: HLIFunction, tuple: HLITuple, dict: HLIDict, list: HLIList, ! types.ModuleType: HLIModule, ! types.CodeType : HLICode, ! types.BuiltinFunctionType : HLIBuiltinFunction, ! types.FrameType : HLIFrame, ! types.TracebackType : HLITraceback, ! str : HLIString, str : HLIString, int: HLIPythonObject, ! int: HLIPythonObject, ! bool: HLIPythonObject, float: HLIPythonObject, } def MakeHLI( ob, name=None ): *************** *** 288,291 **** --- 287,293 ---- cls = TypeMap[type(ob)] except KeyError: + # hrmph - this check gets more and more bogus as Python + # improves. Its possible we should just *always* use + # HLIInstance? if hasattr(ob, '__class__'): # 'new style' class cls = HLIInstance |
From: Mark H. <mha...@us...> - 2009-01-25 04:52:31
|
Update of /cvsroot/pywin32/pywin32/com/win32com/client In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv24579/com/win32com/client Modified Files: Tag: py3k build.py combrowse.py dynamic.py Log Message: merge recent changes from the trunk Index: combrowse.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/client/combrowse.py,v retrieving revision 1.8.2.7 retrieving revision 1.8.2.8 diff -C2 -d -r1.8.2.7 -r1.8.2.8 *** combrowse.py 10 Dec 2008 06:36:01 -0000 1.8.2.7 --- combrowse.py 25 Jan 2009 04:52:20 -0000 1.8.2.8 *************** *** 209,213 **** if extraDescs: extraDesc = " (%s)" % ", ".join(extraDescs) ret.append(HLITypeLib(fname, "Type Library" + extraDesc)) ! ret.sort(key=lambda k:k.GetText()) return ret --- 209,213 ---- if extraDescs: extraDesc = " (%s)" % ", ".join(extraDescs) ret.append(HLITypeLib(fname, "Type Library" + extraDesc)) ! ret.sort() return ret *************** *** 468,472 **** except pythoncom.com_error: ret.append(browser.MakeHLI("The type info can not be loaded!")) ! ret.sort(key=lambda k:k.GetText()) return ret --- 468,472 ---- except pythoncom.com_error: ret.append(browser.MakeHLI("The type info can not be loaded!")) ! ret.sort() return ret *************** *** 514,518 **** win32api.RegCloseKey(key) win32ui.DoWaitCursor(0) ! ret.sort(key=lambda k:k.GetText()) return ret --- 514,518 ---- win32api.RegCloseKey(key) win32ui.DoWaitCursor(0) ! ret.sort() return ret Index: dynamic.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/client/dynamic.py,v retrieving revision 1.22.2.9 retrieving revision 1.22.2.10 diff -C2 -d -r1.22.2.9 -r1.22.2.10 *** dynamic.py 8 Jan 2009 03:45:49 -0000 1.22.2.9 --- dynamic.py 25 Jan 2009 04:52:20 -0000 1.22.2.10 *************** *** 95,103 **** if isinstance(IDispatch, str): userName = IDispatch ! ## elif type(IDispatch) == UnicodeType: ! ## # We always want the displayed name to be a real string ! ## userName = IDispatch.encode("ascii", "replace") ! elif not isinstance(userName, str): ! userName = str(userName) return (_GetGoodDispatch(IDispatch, clsctx), userName) --- 95,105 ---- if isinstance(IDispatch, str): userName = IDispatch ! elif isinstance(IDispatch, str): ! # We always want the displayed name to be a real string ! userName = IDispatch.encode("ascii", "replace") ! elif type(userName) == str: ! # As above - always a string... ! userName = userName.encode("ascii", "replace") ! else: userName = str(userName) return (_GetGoodDispatch(IDispatch, clsctx), userName) Index: build.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/client/build.py,v retrieving revision 1.31.2.8 retrieving revision 1.31.2.9 diff -C2 -d -r1.31.2.8 -r1.31.2.9 *** build.py 14 Jan 2009 12:42:02 -0000 1.31.2.8 --- build.py 25 Jan 2009 04:52:20 -0000 1.31.2.9 *************** *** 390,399 **** assert typeinfo is not None, "Cant build vtables without type info!" - def cmp_vtable_off(m1): - return m1.desc[7] - meth_list = list(self.mapFuncs.values()) + list(self.propMapGet.values()) + list(self.propMapPut.values()) ! meth_list.sort(key = cmp_vtable_off ) # Now turn this list into the run-time representation # (ready for immediate use or writing to gencache) --- 390,402 ---- assert typeinfo is not None, "Cant build vtables without type info!" meth_list = list(self.mapFuncs.values()) + list(self.propMapGet.values()) + list(self.propMapPut.values()) ! if sys.version_info < (2,4): ! def cmp_vtable_off(m1, m2): ! return cmp(m1.desc[7], m2.desc[7]) ! meth_list.sort(cmp_vtable_off) ! else: ! meth_list.sort(key=lambda m: m.desc[7]) ! # Now turn this list into the run-time representation # (ready for immediate use or writing to gencache) |
From: Mark H. <mha...@us...> - 2009-01-25 04:52:26
|
Update of /cvsroot/pywin32/pywin32/win32/src In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv24579/win32/src Modified Files: Tag: py3k PySID.cpp PySecurityObjects.h win32apimodule.cpp win32trace.cpp Log Message: merge recent changes from the trunk Index: win32apimodule.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/win32apimodule.cpp,v retrieving revision 1.89.2.4 retrieving revision 1.89.2.5 diff -C2 -d -r1.89.2.4 -r1.89.2.5 *** win32apimodule.cpp 28 Dec 2008 10:58:11 -0000 1.89.2.4 --- win32apimodule.cpp 25 Jan 2009 04:52:20 -0000 1.89.2.5 *************** *** 105,108 **** --- 105,135 ---- return PyWin_SetAPIError(fnName, err); } + + PyObject *PyTuple_FromSYSTEMTIME(SYSTEMTIME &st) + { + return Py_BuildValue("iiiiiiii", + st.wYear, + st.wMonth, + st.wDayOfWeek, + st.wDay, + st.wHour, + st.wMinute, + st.wSecond, + st.wMilliseconds); + } + + BOOL PyTuple_AsSYSTEMTIME(PyObject *ob, SYSTEMTIME &st) + { + return PyArg_ParseTuple(ob, "iiiiiiii", + &st.wYear, + &st.wMonth, + &st.wDayOfWeek, + &st.wDay, + &st.wHour, + &st.wMinute, + &st.wSecond, + &st.wMilliseconds); + } + // @pymethod |win32api|Beep|Generates simple tones on the speaker. static PyObject * *************** *** 2345,2349 **** PyGetTimeZoneInformation(PyObject * self, PyObject * args) { ! if (!PyArg_ParseTuple (args, ":GetTimeZoneInformation")) return NULL; TIME_ZONE_INFORMATION tzinfo; --- 2372,2378 ---- PyGetTimeZoneInformation(PyObject * self, PyObject * args) { ! int bTimesAsTuples = 0; ! // @pyparm bool|times_as_tuples|False|If true, the SYSTEMTIME elements are returned as tuples instead of a time object. ! if (!PyArg_ParseTuple (args, "|i:GetTimeZoneInformation", &bTimesAsTuples)) return NULL; TIME_ZONE_INFORMATION tzinfo; *************** *** 2370,2377 **** tzinfo.Bias, PyWinObject_FromWCHAR(tzinfo.StandardName), ! PyWinObject_FromSYSTEMTIME(tzinfo.StandardDate), tzinfo.StandardBias, PyWinObject_FromWCHAR(tzinfo.DaylightName), ! PyWinObject_FromSYSTEMTIME(tzinfo.DaylightDate), tzinfo.DaylightBias ); --- 2399,2410 ---- tzinfo.Bias, PyWinObject_FromWCHAR(tzinfo.StandardName), ! bTimesAsTuples ? ! PyTuple_FromSYSTEMTIME(tzinfo.StandardDate) : ! PyWinObject_FromSYSTEMTIME(tzinfo.StandardDate), tzinfo.StandardBias, PyWinObject_FromWCHAR(tzinfo.DaylightName), ! bTimesAsTuples ? ! PyTuple_FromSYSTEMTIME(tzinfo.DaylightDate) : ! PyWinObject_FromSYSTEMTIME(tzinfo.DaylightDate), tzinfo.DaylightBias ); *************** *** 2385,2393 **** // @tupleitem 0|int|bias|Specifies the current bias, in minutes, for local time translation on this computer. The bias is the difference, in minutes, between Coordinated Universal Time (UTC) and local time. All translations between UTC and local time are based on the following formula:<nl><nl>UTC = local time + bias <nl><nl> // @tupleitem 1|unicode|standardName|Specifies a string associated with standard time on this operating system. For example, this member could contain "EST" to indicate Eastern Standard Time. This string is not used by the operating system, so anything stored there using the SetTimeZoneInformation function is returned unchanged by the GetTimeZoneInformation function. This string can be empty. ! // @tupleitem 2|<o PyTime>|standardTime|Specifies a SYSTEMTIME object that contains a date and local time when the transition from daylight saving time to standard time occurs on this operating system. If this date is not specified, the wMonth member in the SYSTEMTIME structure must be zero. If this date is specified, the DaylightDate value in the TIME_ZONE_INFORMATION structure must also be specified. // <nl>To select the correct day in the month, set the wYear member to zero, the wDayOfWeek member to an appropriate weekday, and the wDay member to a value in the range 1 through 5. Using this notation, the first Sunday in April can be specified, as can the last Thursday in October (5 is equal to "the last"). // @tupleitem 3|int|standardBias|Specifies a bias value to be used during local time translations that occur during standard time. This member is ignored if a value for the StandardDate member is not supplied. <nl>This value is added to the value of the Bias member to form the bias used during standard time. In most time zones, the value of this member is zero. // @tupleitem 4|unicode|daylightName| ! // @tupleitem 5|<o PyTime>|daylightTime| // @tupleitem 6|int|daylightBias|Specifies a bias value to be used during local time translations that occur during daylight saving time. This member is ignored if a value for the DaylightDate member is not supplied. // <nl>This value is added to the value of the Bias member to form the bias used during daylight saving time. In most time zones, the value of this member is 60. --- 2418,2426 ---- // @tupleitem 0|int|bias|Specifies the current bias, in minutes, for local time translation on this computer. The bias is the difference, in minutes, between Coordinated Universal Time (UTC) and local time. All translations between UTC and local time are based on the following formula:<nl><nl>UTC = local time + bias <nl><nl> // @tupleitem 1|unicode|standardName|Specifies a string associated with standard time on this operating system. For example, this member could contain "EST" to indicate Eastern Standard Time. This string is not used by the operating system, so anything stored there using the SetTimeZoneInformation function is returned unchanged by the GetTimeZoneInformation function. This string can be empty. ! // @tupleitem 2|<o PyTime>/tuple|standardTime|Specifies a SYSTEMTIME object that contains a date and local time when the transition from daylight saving time to standard time occurs on this operating system. If this date is not specified, the wMonth member in the SYSTEMTIME structure must be zero. If this date is specified, the DaylightDate value in the TIME_ZONE_INFORMATION structure must also be specified. // <nl>To select the correct day in the month, set the wYear member to zero, the wDayOfWeek member to an appropriate weekday, and the wDay member to a value in the range 1 through 5. Using this notation, the first Sunday in April can be specified, as can the last Thursday in October (5 is equal to "the last"). // @tupleitem 3|int|standardBias|Specifies a bias value to be used during local time translations that occur during standard time. This member is ignored if a value for the StandardDate member is not supplied. <nl>This value is added to the value of the Bias member to form the bias used during standard time. In most time zones, the value of this member is zero. // @tupleitem 4|unicode|daylightName| ! // @tupleitem 5|<o PyTime>/tuple|daylightTime| // @tupleitem 6|int|daylightBias|Specifies a bias value to be used during local time translations that occur during daylight saving time. This member is ignored if a value for the DaylightDate member is not supplied. // <nl>This value is added to the value of the Bias member to form the bias used during daylight saving time. In most time zones, the value of this member is 60. *************** *** 2395,2398 **** --- 2428,2483 ---- } + // @pymethod tuple|win32api|SetTimeZoneInformation|Sets the system time-zone information. + static PyObject * + PySetTimeZoneInformation(PyObject * self, PyObject * args) + { + // @pyparm tuple|tzi||A tuple with the timezone info + // @desc The tuple is of form. + TIME_ZONE_INFORMATION tzi; + PyObject *obStdName, *obStdDate; + PyObject *obDaylightName, *obDaylightDate; + if (!PyArg_ParseTuple (args, "(iOOiOOi):SetTimeZoneInformation", + &tzi.Bias, // @tupleitem 0|int|Bias| + &obStdName, // @tupleitem 1|string|StandardName + &obStdDate, // @tupleitem 2|SYSTEMTIME tuple|StandardDate + &tzi.StandardBias, // @tupleitem 3|int|StandardBias + &obDaylightName, // @tupleitem 4|string|DaylightName + &obDaylightDate, // @tupleitem 5|SYSTEMTIME tuple|DaylightDate + &tzi.DaylightBias))// @tupleitem 6|int|DaylightBias + return NULL; + WCHAR *temp; + if (!PyWinObject_AsWCHAR(obStdName, &temp)) + return NULL; + if (wcslen(temp)>31) { + PyWinObject_FreeWCHAR(temp); + return PyErr_Format(PyExc_ValueError, "Time zone names must be < 32 chars long"); + } + wcscpy(tzi.StandardName, temp); + PyWinObject_FreeWCHAR(temp); + // second string... + if (!PyWinObject_AsWCHAR(obDaylightName, &temp)) + return NULL; + if (wcslen(temp)>31) { + PyWinObject_FreeWCHAR(temp); + return PyErr_Format(PyExc_ValueError, "Time zone names must be < 32 chars long"); + } + wcscpy(tzi.DaylightName, temp); + PyWinObject_FreeWCHAR(temp); + + // tuples with a SYSTEMTIME + if (!PyTuple_AsSYSTEMTIME(obStdDate, tzi.StandardDate)) + return NULL; + if (!PyTuple_AsSYSTEMTIME(obDaylightDate, tzi.DaylightDate)) + return NULL; + + BOOL rc; + PyW32_BEGIN_ALLOW_THREADS + rc = ::SetTimeZoneInformation(&tzi); + PyW32_END_ALLOW_THREADS + if(!rc) + return ReturnAPIError("SetTimeZoneInformation"); + Py_RETURN_NONE; + } + // @pymethod string|win32api|GetDateFormat|Formats a date as a date string for a specified locale. The function formats either a specified date or the local system date. static PyObject *PyGetDateFormat(PyObject *self, PyObject *args) *************** *** 6240,6243 **** --- 6325,6329 ---- {"SetSystemPowerState", PySetSystemPowerState, 1}, // @pymeth SetSystemPowerState|Powers machine down to a suspended state {"SetThreadLocale", PySetThreadLocale, 1}, // @pymeth SetThreadLocale|Sets the current thread's locale. + {"SetTimeZoneInformation",PySetTimeZoneInformation,1}, // @pymeth SetTimeZoneInformation|Sets the system time-zone information. {"SetWindowLong", PySetWindowLong,1}, // @pymeth SetWindowLong|Places a long value at the specified offset into the extra window memory of the given window. {"ShellExecute", PyShellExecute, 1}, // @pymeth ShellExecute|Executes an application. Index: win32trace.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/win32trace.cpp,v retrieving revision 1.14.2.5 retrieving revision 1.14.2.6 diff -C2 -d -r1.14.2.5 -r1.14.2.6 *** win32trace.cpp 14 Jan 2009 12:42:03 -0000 1.14.2.5 --- win32trace.cpp 25 Jan 2009 04:52:20 -0000 1.14.2.6 *************** *** 115,129 **** } static PyObject *PyTraceObject_write(PyObject *self, PyObject *args) { int len; ! char *data; ! if (!PyArg_ParseTuple(args, "s#:write", &data, &len)) return NULL; BOOL ok = static_cast<PyTraceObject*>(self)->WriteData(data, len); if (!ok) return NULL; ! Py_INCREF(Py_None); ! return Py_None; } --- 115,133 ---- } + // In an attempt to allow py2k and py3k readers and writers to work together, + // we assume a 'latin1' encoding for the bytes on the wire. When pulling the + // bytes off the wire, in py2k we return a string while in py3k we return + // a latin-1 decoded unicode object. static PyObject *PyTraceObject_write(PyObject *self, PyObject *args) { int len; ! char *data = NULL; ! if (!PyArg_ParseTuple(args, "et#:write", "latin-1", &data, &len)) return NULL; BOOL ok = static_cast<PyTraceObject*>(self)->WriteData(data, len); + PyMem_Free(data); if (!ok) return NULL; ! Py_RETURN_NONE; } *************** *** 137,141 **** --- 141,149 ---- if (!ok) return NULL; + #if (PY_VERSION_HEX < 0x03000000) PyObject *result = PyString_FromStringAndSize(data, len); + #else + PyObject *result = PyUnicode_DecodeLatin1(data, len, "replace"); + #endif free(data); return result; *************** *** 152,156 **** --- 160,168 ---- if (!ok) return NULL; + #if (PY_VERSION_HEX < 0x03000000) PyObject *result = PyString_FromStringAndSize(data, len); + #else + PyObject *result = PyUnicode_DecodeLatin1(data, len, "replace"); + #endif free(data); return result; *************** *** 648,651 **** --- 660,664 ---- // no local one exists - see if we can create it globally - if // we can, we go global, else we stick with local. + use_global_namespace = TRUE; HANDLE h2 = CreateFileMapping((HANDLE)-1, &sa, PAGE_READWRITE, 0, BUFFER_SIZE, Index: PySecurityObjects.h =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/PySecurityObjects.h,v retrieving revision 1.13.2.1 retrieving revision 1.13.2.2 diff -C2 -d -r1.13.2.1 -r1.13.2.2 *** PySecurityObjects.h 29 Aug 2008 04:59:25 -0000 1.13.2.1 --- PySecurityObjects.h 25 Jan 2009 04:52:20 -0000 1.13.2.2 *************** *** 102,108 **** --- 102,110 ---- /* Python support */ int compare(PyObject *ob); + PyObject *richcompare(PyObject *other, int op); static void deallocFunc(PyObject *ob); static int compareFunc(PyObject *ob1, PyObject *ob2); + static PyObject *richcompareFunc(PyObject *ob1, PyObject *ob2, int op); static PyObject *strFunc(PyObject *ob); Index: PySID.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/PySID.cpp,v retrieving revision 1.12.2.1 retrieving revision 1.12.2.2 diff -C2 -d -r1.12.2.1 -r1.12.2.2 *** PySID.cpp 29 Aug 2008 04:59:25 -0000 1.12.2.1 --- PySID.cpp 25 Jan 2009 04:52:20 -0000 1.12.2.2 *************** *** 261,265 **** 0, /* tp_traverse */ 0, /* tp_clear */ ! 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ --- 261,265 ---- 0, /* tp_traverse */ 0, /* tp_clear */ ! PySID::richcompareFunc, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ *************** *** 314,317 **** --- 314,336 ---- } + PyObject *PySID::richcompare(PyObject *other, int op) + { + BOOL e; + if (PySID_Check(other)) + e=compare((PyHANDLE *)other)==0; + else + e=FALSE; + PyObject *ret; + if (op==Py_EQ) + ret = e ? Py_True : Py_False; + else if (op==Py_NE) + ret = !e ? Py_True : Py_False; + else { + PyErr_SetString(PyExc_TypeError, "SIDs only compare equal or not equal"); + ret = NULL; + } + Py_XINCREF(ret); + return ret; + } // @pymethod int|PySID|__cmp__|Used when objects are compared. *************** *** 322,325 **** --- 341,349 ---- } + PyObject *PySID::richcompareFunc(PyObject *ob1, PyObject *ob2, int op) + { + return ((PySID *)ob1)->richcompare(ob2, op); + } + /*static*/ void PySID::deallocFunc(PyObject *ob) { |
From: Mark H. <mha...@us...> - 2009-01-25 03:35:19
|
Update of /cvsroot/pywin32/pywin32/com/win32com/client In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv307/com/win32com/client Modified Files: build.py Log Message: sort the vtable entries in a py2k and py3k-friendly way Index: build.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/client/build.py,v retrieving revision 1.38 retrieving revision 1.39 diff -C2 -d -r1.38 -r1.39 *** build.py 9 Jan 2009 01:29:29 -0000 1.38 --- build.py 25 Jan 2009 03:35:15 -0000 1.39 *************** *** 390,399 **** assert typeinfo is not None, "Cant build vtables without type info!" - def cmp_vtable_off(m1, m2): - return cmp(m1.desc[7], m2.desc[7]) - meth_list = list(self.mapFuncs.values()) + list(self.propMapGet.values()) + list(self.propMapPut.values()) ! meth_list.sort( cmp_vtable_off ) # Now turn this list into the run-time representation # (ready for immediate use or writing to gencache) --- 390,402 ---- assert typeinfo is not None, "Cant build vtables without type info!" meth_list = list(self.mapFuncs.values()) + list(self.propMapGet.values()) + list(self.propMapPut.values()) ! if sys.version_info < (2,4): ! def cmp_vtable_off(m1, m2): ! return cmp(m1.desc[7], m2.desc[7]) ! meth_list.sort(cmp_vtable_off) ! else: ! meth_list.sort(key=lambda m: m.desc[7]) ! # Now turn this list into the run-time representation # (ready for immediate use or writing to gencache) |