pywin32-checkins Mailing List for Python for Windows Extensions (Page 23)
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-28 10:48:26
|
Update of /cvsroot/pywin32/pywin32/AutoDuck In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv391 Modified Files: pywin32-document.xml Log Message: include py3k doc in the index Index: pywin32-document.xml =================================================================== RCS file: /cvsroot/pywin32/pywin32/AutoDuck/pywin32-document.xml,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** pywin32-document.xml 24 May 2008 08:17:54 -0000 1.7 --- pywin32-document.xml 28 Jan 2009 10:48:21 -0000 1.8 *************** *** 2,5 **** --- 2,6 ---- <important> <item name="View the change log" href="html/CHANGES.txt"/> + <item name="View information regarding Python 3.x support" href="html/win32/help/py3k.html"/> </important> <links> |
From: Mark H. <mha...@us...> - 2009-01-28 10:47:49
|
Update of /cvsroot/pywin32/pywin32/win32/help In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv303 Added Files: py3k.html Log Message: Pleaseholder for info about py3k support. --- NEW FILE: py3k.html --- <html> <head> <TITLE>Python 3.x support</TITLE> </head> <body> <h1>Introduction</h1> <p> pywin32 now supports Python 3.x. Note that the Python source code is maintained in Python 2.x syntax and automatically converted to Python 3.x syntax using the 2to3 tool. Please don't submit patches etc using Python 3.x syntax. </p> <h1>Unicode everywhere</h1> <p> In general, pywin32 on Python 2.x will accept both str and unicode objects and convert as appropriate. In Python 3.x byte() objects are generally not accepted; strings must be unicode. </p> <p> Most pywin32 modules for py3k are built with UNICODE defined, and thus will call the Unicode versions of the Windows API. </p> <h1>datetime objects</h1> <p> Python 3.x builds use a subclass of datetime.datetime objects as the "native" datetime object; a subclass is used to provive a backwards compatible <a href="PyDateTime__Format_meth.html">PyDateTime.Format</a> method, but otherwise the datetime object is identical to the base class. All time objects returned by pywin32 will have a UTC timezone (via the win32timezone module), and times with any timezone will be accepted when passed to pywin32 - but "time zone naive" objects are *not* supported. </p> <p> The <a href="win32timezone__now_meth.html">win32timezone.now</a> and <a href="win32timezone__utcnow_meth.html">win32timezone.utcnow</a> methods may be useful when working with datetime objects. </p> </body> </html> |
From: Mark H. <mha...@us...> - 2009-01-28 10:47:17
|
Update of /cvsroot/pywin32/pywin32/AutoDuck In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv32745 Modified Files: py2d.py Log Message: improve .d generation for modules with doctests Index: py2d.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/AutoDuck/py2d.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** py2d.py 11 Sep 2004 07:43:38 -0000 1.1 --- py2d.py 28 Jan 2009 10:47:10 -0000 1.2 *************** *** 1,4 **** --- 1,8 ---- import sys import types + import re + + def ad_escape(s): + return re.sub(r"([^<]*)<([^>]*)>", r"\g<1>\\<\g<2>\\>", s) class DocInfo: *************** *** 19,23 **** info.default = "" if len(defs): ! info.default = defs.pop() ret.append(info) ret.reverse() --- 23,30 ---- info.default = "" if len(defs): ! default = repr(defs.pop()) ! # the default may be an object, so the repr gives '<...>' - and ! # the angle brackets screw autoduck. ! info.default = default.replace("<", "").replace(">", "") ret.append(info) ret.reverse() *************** *** 32,45 **** return ret def format_desc(desc): if not desc: return "" ! lines = desc.splitlines() ! chunks = [lines[0]] ! for line in lines[1:]: ! line = line.strip() ! if not line: ! line = "<nl>" ! chunks.append( "// " + line ) return "\n".join(chunks) --- 39,85 ---- return ret + def should_build_function(build_info): + return build_info.ob.__doc__ and not build_info.ob.__name__.startswith('_') + + # docstring aware paragraph generator. Isn't there something in docutils + # we can use? + def gen_paras(val): + chunks = [] + in_docstring = False + for line in val.splitlines(): + line = ad_escape(line.strip()) + if not line or (not in_docstring and line.startswith(">>> ")): + if chunks: + yield chunks + chunks = [] + if not line: + in_docstring = False + continue + in_docstring = True + chunks.append(line) + yield chunks or [''] + def format_desc(desc): + # A little complicated! Given the docstring for a module, we want to: + # write: + # 'first_para_of_docstring' + # '@comm next para of docstring' + # '@comm next para of docstring' ... etc + # BUT - also handling enbedded doctests, where we write + # '@iex >>> etc.' if not desc: return "" ! g = gen_paras(desc) ! first = g.next() ! chunks = [first[0]] ! chunks.extend(["// " + l for l in first[1:]]) ! for lines in g: ! first = lines[0] ! if first.startswith(">>> "): ! prefix = "// @iex \n// " ! else: ! prefix = "\n// @comm " ! chunks.append(prefix + first) ! chunks.extend(["// " + l for l in lines[1:]]) return "\n".join(chunks) *************** *** 55,59 **** if hasattr(ob, "__module__") and ob.__module__ != mod_name: continue ! if type(ob)==types.ClassType: classes.append(BuildInfo(name, ob)) elif type(ob)==types.FunctionType: --- 95,99 ---- if hasattr(ob, "__module__") and ob.__module__ != mod_name: continue ! if type(ob) in [types.ClassType, type]: classes.append(BuildInfo(name, ob)) elif type(ob)==types.FunctionType: *************** *** 63,68 **** --- 103,115 ---- info = BuildInfo(mod_name, mod) print >> fp, "// @module %s|%s" % (mod_name, format_desc(info.desc)) + functions = [f for f in functions if should_build_function(f)] for ob in functions: print >> fp, "// @pymeth %s|%s" % (ob.name, ob.short_desc) + for ob in classes: + # only classes with docstrings get printed. + if not ob.ob.__doc__: + continue + ob_name = mod_name + "." + ob.name + print >> fp, "// @pyclass %s|%s" % (ob.name, ob.short_desc) for ob in functions: print >> fp, "// @pymethod |%s|%s|%s" % (mod_name, ob.name, format_desc(ob.desc)) *************** *** 71,85 **** for ob in classes: ob_name = mod_name + "." + ob.name print >> fp, "// @object %s|%s" % (ob_name, format_desc(ob.desc)) func_infos = [] ! for n, o in ob.ob.__dict__.items(): ! if type(o)==types.FunctionType: info = BuildInfo(n, o) ! func_infos.append(info) for fi in func_infos: print >> fp, "// @pymeth %s|%s" % (fi.name, fi.short_desc) for fi in func_infos: print >> fp, "// @pymethod |%s|%s|%s" % (ob_name, fi.name, format_desc(fi.desc)) for ai in BuildArgInfos(fi.ob): print >> fp, "// @pyparm |%s|%s|%s" % (ai.name, ai.default, ai.short_desc) --- 118,142 ---- for ob in classes: + # only classes with docstrings get printed. + if not ob.ob.__doc__: + continue ob_name = mod_name + "." + ob.name print >> fp, "// @object %s|%s" % (ob_name, format_desc(ob.desc)) func_infos = [] ! # We need to iter the keys then to a getattr() so the funky descriptor ! # things work. ! for n in ob.ob.__dict__.iterkeys(): ! o = getattr(ob.ob, n) ! if isinstance(o, (types.FunctionType, types.MethodType)): info = BuildInfo(n, o) ! if should_build_function(info): ! func_infos.append(info) for fi in func_infos: print >> fp, "// @pymeth %s|%s" % (fi.name, fi.short_desc) for fi in func_infos: print >> fp, "// @pymethod |%s|%s|%s" % (ob_name, fi.name, format_desc(fi.desc)) + if hasattr(fi.ob, 'im_self') and fi.ob.im_self is ob.ob: + print >> fp, "// @comm This is a @classmethod." + print >> fp, "// @pymethod |%s|%s|%s" % (ob_name, fi.name, format_desc(fi.desc)) for ai in BuildArgInfos(fi.ob): print >> fp, "// @pyparm |%s|%s|%s" % (ai.name, ai.default, ai.short_desc) |
From: Mark H. <mha...@us...> - 2009-01-28 10:46:01
|
Update of /cvsroot/pywin32/pywin32/AutoDuck In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv32636 Modified Files: pyhtml.fmt Log Message: Fix html generation for iex tag and add pyclass tag Index: pyhtml.fmt =================================================================== RCS file: /cvsroot/pywin32/pywin32/AutoDuck/pyhtml.fmt,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** pyhtml.fmt 4 May 2008 12:59:57 -0000 1.12 --- pyhtml.fmt 28 Jan 2009 10:45:56 -0000 1.13 *************** *** 260,263 **** --- 260,270 ---- .post=$(deflist_e) + .tag=pyclass, html, 2, 2 + .pre=$(rmh)Classes$(rmhe)$(par)$(deflist) + .format=$(term1)<A HREF="#module.1.#1.html">$1</A>$(line) + $(def1)$2 $(par) + .post=$(deflist_e) + .if=exists($module.1) + .tag=pymeth, html, 2, 2 .pre=$(rmh)Methods$(rmhe)$(par)$(deflist) *************** *** 521,526 **** .tag=iex, html, 1, 8, 1 ! .format=$(ex)$1$(par) ! $(ex)$(par) .post=$(exe) --- 528,533 ---- .tag=iex, html, 1, 8, 1 ! .pre=$(ex) ! .format=$1$(par) .post=$(exe) |
From: Mark H. <mha...@us...> - 2009-01-27 14:16:52
|
Update of /cvsroot/pywin32/pywin32/win32/src In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv31258/win32/src Modified Files: win32inet_winhttp.cpp win32apimodule.cpp PyTime.cpp Log Message: autoduck Index: win32apimodule.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/win32apimodule.cpp,v retrieving revision 1.96 retrieving revision 1.97 diff -C2 -d -r1.96 -r1.97 *** win32apimodule.cpp 25 Jan 2009 23:49:17 -0000 1.96 --- win32apimodule.cpp 27 Jan 2009 13:07:19 -0000 1.97 *************** *** 2433,2437 **** { // @pyparm tuple|tzi||A tuple with the timezone info ! // @desc The tuple is of form. TIME_ZONE_INFORMATION tzi; PyObject *obStdName, *obStdDate; --- 2433,2437 ---- { // @pyparm tuple|tzi||A tuple with the timezone info ! // @comm The tuple is of form: TIME_ZONE_INFORMATION tzi; PyObject *obStdName, *obStdDate; *************** *** 2439,2448 **** 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; --- 2439,2448 ---- 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; Index: win32inet_winhttp.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/win32inet_winhttp.cpp,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** win32inet_winhttp.cpp 17 Dec 2008 13:05:38 -0000 1.4 --- win32inet_winhttp.cpp 27 Jan 2009 13:07:16 -0000 1.5 *************** *** 129,133 **** i->dwAccessType, // @tupleitem 0|int|dwAccessType| i->lpszProxy, // @tupleitem 2|string|lpszProxy| ! i->lpszProxyBypass); // @tupleitem 3|string|lpszProxy if (i->lpszProxy) GlobalFree(i->lpszProxy); if (i->lpszProxyBypass) GlobalFree(i->lpszProxyBypass); --- 129,133 ---- i->dwAccessType, // @tupleitem 0|int|dwAccessType| i->lpszProxy, // @tupleitem 2|string|lpszProxy| ! i->lpszProxyBypass); // @tupleitem 3|string|lpszProxy| if (i->lpszProxy) GlobalFree(i->lpszProxy); if (i->lpszProxyBypass) GlobalFree(i->lpszProxyBypass); Index: PyTime.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/PyTime.cpp,v retrieving revision 1.26 retrieving revision 1.27 diff -C2 -d -r1.26 -r1.27 *** PyTime.cpp 26 Jan 2009 01:23:38 -0000 1.26 --- PyTime.cpp 27 Jan 2009 13:07:19 -0000 1.27 *************** *** 684,695 **** #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) --- 684,695 ---- #ifdef PYWIN_HAVE_DATETIME_CAPI // @object PyDateTime|A Python object, representing an instant in time. ! // @comm pywin32 builds for Python 3.0 use datetime objects instead of the // old PyTime object. ! // @comm 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. ! // @pymethod str|PyDateTime|Format| ! // @comm 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) |
From: Mark H. <mha...@us...> - 2009-01-27 14:16:48
|
Update of /cvsroot/pywin32/pywin32/isapi/src In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv31258/isapi/src Modified Files: PyExtensionObjects.cpp Log Message: autoduck Index: PyExtensionObjects.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/isapi/src/PyExtensionObjects.cpp,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** PyExtensionObjects.cpp 3 Jan 2009 06:11:46 -0000 1.13 --- PyExtensionObjects.cpp 27 Jan 2009 13:07:21 -0000 1.14 *************** *** 766,770 **** return SetPyECBError("ServerSupportFunction(HSE_REQ_GET_EXEC_URL_STATUS)"); // @rdesc The result of a tuple of 3 integers - (uHttpStatusCode, uHttpSubStatus, dwWin32Error) ! // @seeapi HSE_EXEC_URL_STATUS return Py_BuildValue("HHk", status.uHttpStatusCode, status.uHttpSubStatus, status.dwWin32Error); } --- 766,770 ---- return SetPyECBError("ServerSupportFunction(HSE_REQ_GET_EXEC_URL_STATUS)"); // @rdesc The result of a tuple of 3 integers - (uHttpStatusCode, uHttpSubStatus, dwWin32Error) ! // @pyseeapi HSE_EXEC_URL_STATUS return Py_BuildValue("HHk", status.uHttpStatusCode, status.uHttpSubStatus, status.dwWin32Error); } |
From: Mark H. <mha...@us...> - 2009-01-27 14:16:45
|
Update of /cvsroot/pywin32/pywin32/SWIG/swig_lib/python In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv31400/SWIG/swig_lib/python Modified Files: pywintypes.i Log Message: checkin forgotten header consolidation change Index: pywintypes.i =================================================================== RCS file: /cvsroot/pywin32/pywin32/SWIG/swig_lib/python/pywintypes.i,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** pywintypes.i 4 Jan 2009 13:44:19 -0000 1.8 --- pywintypes.i 27 Jan 2009 13:08:02 -0000 1.9 *************** *** 36,44 **** %{ #include "PyWinTypes.h" #ifdef NEED_PYWINOBJECTS_H #include "PyWinObjects.h" #endif - #include "winbase.h" #include "tchar.h" %} --- 36,45 ---- %{ + #include "windows.h" + #include "winbase.h" #include "PyWinTypes.h" #ifdef NEED_PYWINOBJECTS_H #include "PyWinObjects.h" #endif #include "tchar.h" %} |
From: Mark H. <mha...@us...> - 2009-01-27 14:16:41
|
Update of /cvsroot/pywin32/pywin32 In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv31607 Modified Files: setup.py Added Files: setup3.py Log Message: merge final py3k build support Index: setup.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/setup.py,v retrieving revision 1.94 retrieving revision 1.95 diff -C2 -d -r1.94 -r1.95 *** setup.py 25 Jan 2009 23:49:17 -0000 1.94 --- setup.py 27 Jan 2009 13:09:09 -0000 1.95 *************** *** 97,100 **** --- 97,103 ---- from distutils.command.build import build from distutils.command.install_data import install_data + from distutils.command.build_py import build_py + from distutils.command.build_scripts import build_scripts + try: from distutils.command.bdist_msi import bdist_msi *************** *** 527,530 **** --- 530,608 ---- ################################################################ + # Extensions to the distutils commands. + + # Start with 2to3 related stuff for py3k. + do_2to3 = is_py3k + if do_2to3: + def refactor_filenames(filenames): + from lib2to3.refactor import RefactoringTool + # we only need some fixers. + fixers = """basestring exec except dict import imports next nonzero + print raw_input long standarderror types unicode urllib + xrange""".split() + fqfixers = ['lib2to3.fixes.fix_' + f for f in fixers] + + options = dict(doctests_only=False, fix=[], list_fixes=[], + print_function=False, verbose=False, + write=True) + r = RefactoringTool(fqfixers, options) + for updated_file in filenames: + if os.path.splitext(updated_file)[1] not in ['.py', '.pys']: + continue + log.info("Refactoring %s" % updated_file) + try: + r.refactor_file(updated_file, write=True, doctests_only=False) + if os.path.exists(updated_file + ".bak"): + os.unlink(updated_file + ".bak") + except Exception: + log.warn("WARNING: Failed to 2to3 %s: %s" % (updated_file, sys.exc_info()[1])) + else: + # py2k - nothing to do. + def refactor_filenames(filenames): + pass + + # 'build_py' command + if do_2to3: + # Force 2to3 to be run for py3k versions. + class my_build_py(build_py): + def run(self): + self.updated_files = [] + + # Base class code + if self.py_modules: + self.build_modules() + if self.packages: + self.build_packages() + self.build_package_data() + + # 2to3 + refactor_filenames(self.updated_files) + + # Remaining base class code + self.byte_compile(self.get_outputs(include_bytecode=0)) + + def build_module(self, module, module_file, package): + res = build_py.build_module(self, module, module_file, package) + if res[1]: + # file was copied + self.updated_files.append(res[0]) + return res + else: + my_build_py = build_py # default version. + + # 'build_scripts' command + if do_2to3: + class my_build_scripts(build_scripts): + def copy_file(self, src, dest): + dest, copied = build_scripts.copy_file(self, src, dest) + # 2to3 + if not self.dry_run and copied: + refactor_filenames([dest]) + return dest, copied + + else: + my_build_scripts = build_scripts + + # 'build' command class my_build(build): def run(self): *************** *** 1340,1343 **** --- 1418,1428 ---- install_data.finalize_options(self) + def copy_file(self, src, dest): + dest, copied = install_data.copy_file(self, src, dest) + # 2to3 + if not self.dry_run and copied: + refactor_filenames([dest]) + return dest, copied + ################################################################ *************** *** 1930,1933 **** --- 2015,2023 ---- other_extensions + if is_py3k: + py3k_skip_modules = \ + """adsi mapi isapi PyISAPI_loader""".split() + ext_modules = [e for e in ext_modules if e.name not in py3k_skip_modules] + # Build a map of DLL base addresses. According to Python's PC\dllbase_nt.txt, # we start at 0x1e200000 and go up in 0x00020000 increments. A couple of *************** *** 1948,1951 **** --- 2038,2043 ---- 'build_ext': my_build_ext, 'install_data': my_install_data, + 'build_py' : my_build_py, + 'build_scripts' : my_build_scripts, } --- NEW FILE: setup3.py --- # This is a Python 3.x script to build pywin32. It converts then executes # the regular setup.py script. import os from lib2to3.refactor import RefactoringTool, get_fixers_from_package fixers = ['lib2to3.fixes.fix_print', 'lib2to3.fixes.fix_except'] options = dict(doctests_only=False, fix=[], list_fixes=[], print_function=False, verbose=False, write=True) r = RefactoringTool(fixers, options) script = os.path.join(os.path.dirname(__file__), "setup.py") data = open(script).read() print("Converting...") got = r.refactor_string(data, "setup.py") print("Executing...") exec(str(got)) |
From: Mark H. <mha...@us...> - 2009-01-27 07:56:56
|
Update of /cvsroot/pywin32/pywin32/win32/Lib In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv19500/win32/Lib Modified Files: Tag: py3k pywintypes.py Log Message: merge various trunk changes Index: pywintypes.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/Lib/pywintypes.py,v retrieving revision 1.13.2.1 retrieving revision 1.13.2.2 diff -C2 -d -r1.13.2.1 -r1.13.2.2 *** pywintypes.py 29 Aug 2008 04:59:25 -0000 1.13.2.1 --- pywintypes.py 27 Jan 2009 07:56:45 -0000 1.13.2.2 *************** *** 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,109 **** # give up in disgust. raise ImportError("No system module '%s' (%s)" % (modname, filename)) # Python can load the module - ## print ('__import_pywin32_system_module__ (before):', __import_pywin32_system_module__) mod = imp.load_dynamic(modname, found) ! ## print ('mod:', mod) ! ## print ('__import_pywin32_system_module__ (after):', __import_pywin32_system_module__) ! # and fill our namespace with it. ! # This doesn't work in py3k, where pywintypes actually ends up as the compiled pyd ! # which is loaded, rather than this script ! ## globs.update(mod.__dict__) ! mod.__import_pywin32_system_module__ = __import_pywin32_system_module__ ! __import_pywin32_system_module__("pywintypes", {}) --- 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-27 07:56:56
|
Update of /cvsroot/pywin32/pywin32 In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv19500 Modified Files: Tag: py3k CHANGES.txt pywin32_postinstall.py setup.py Log Message: merge various trunk changes Index: pywin32_postinstall.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/pywin32_postinstall.py,v retrieving revision 1.25.2.5 retrieving revision 1.25.2.6 diff -C2 -d -r1.25.2.5 -r1.25.2.6 *** pywin32_postinstall.py 5 Jan 2009 12:51:26 -0000 1.25.2.5 --- pywin32_postinstall.py 27 Jan 2009 07:56:44 -0000 1.25.2.6 *************** *** 368,372 **** RegisterCOMObjects() except win32api.error as details: ! if details[0]!=5: # ERROR_ACCESS_DENIED raise print("You do not have the permissions to install COM objects.") --- 368,372 ---- RegisterCOMObjects() except win32api.error as details: ! if details.winerror!=5: # ERROR_ACCESS_DENIED raise print("You do not have the permissions to install COM objects.") Index: setup.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/setup.py,v retrieving revision 1.81.2.15 retrieving revision 1.81.2.16 diff -C2 -d -r1.81.2.15 -r1.81.2.16 *** setup.py 25 Jan 2009 04:52:19 -0000 1.81.2.15 --- setup.py 27 Jan 2009 07:56:44 -0000 1.81.2.16 *************** *** 266,269 **** --- 266,270 ---- 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" *************** *** 272,275 **** --- 273,278 ---- '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: *************** *** 400,403 **** --- 403,411 ---- 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: *************** *** 1443,1447 **** ("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'), --- 1451,1454 ---- *************** *** 1502,1505 **** --- 1509,1520 ---- # 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 = """ Index: CHANGES.txt =================================================================== RCS file: /cvsroot/pywin32/pywin32/CHANGES.txt,v retrieving revision 1.26.2.8 retrieving revision 1.26.2.9 diff -C2 -d -r1.26.2.8 -r1.26.2.9 *** CHANGES.txt 5 Jan 2009 12:51:26 -0000 1.26.2.8 --- CHANGES.txt 27 Jan 2009 07:56:44 -0000 1.26.2.9 *************** *** 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: |
Update of /cvsroot/pywin32/pywin32/win32/src In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv19500/win32/src Modified Files: Tag: py3k PyTime.cpp PyWinTypesmodule.cpp win32apimodule.cpp win32pipe.i win32rasmodule.cpp Log Message: merge various trunk changes Index: win32apimodule.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/win32apimodule.cpp,v retrieving revision 1.89.2.5 retrieving revision 1.89.2.6 diff -C2 -d -r1.89.2.5 -r1.89.2.6 *** win32apimodule.cpp 25 Jan 2009 04:52:20 -0000 1.89.2.5 --- win32apimodule.cpp 27 Jan 2009 07:56:45 -0000 1.89.2.6 *************** *** 6065,6069 **** } - /* // @pymethod dict|win32api|GetPwrCapabilities|Retrieves system's power capabilities // @pyseeapi GetPwrCapabilities --- 6065,6068 ---- *************** *** 6111,6115 **** "DefaultLowLatencyWake", PyInt_FromLong(spc.DefaultLowLatencyWake)); } - */ /* List of functions exported by this module */ --- 6110,6113 ---- *************** *** 6211,6217 **** {"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. --- 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. Index: win32rasmodule.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/win32rasmodule.cpp,v retrieving revision 1.10.2.4 retrieving revision 1.10.2.5 diff -C2 -d -r1.10.2.4 -r1.10.2.5 *** win32rasmodule.cpp 8 Dec 2008 13:41:06 -0000 1.10.2.4 --- win32rasmodule.cpp 27 Jan 2009 07:56:45 -0000 1.10.2.5 *************** *** 14,23 **** #ifndef WINVER // hrm - the RASEAPUSERIDENTITY structures on the Vista SDK now want ! // a WINVER > 0x500. ! # ifdef _WIN64 ! # define WINVER 0x501 ! # else ! # define WINVER 0x400 ! # endif #endif --- 14,18 ---- #ifndef WINVER // hrm - the RASEAPUSERIDENTITY structures on the Vista SDK now want ! #define WINVER 0x501 #endif *************** *** 91,97 **** if (pfnPyWinObject_AsRASEAPUSERIDENTITY == NULL) { #ifdef _DEBUG ! HMODULE hmod = GetModuleHandle("win2kras_d.pyd"); #else ! HMODULE hmod = GetModuleHandle("win2kras.pyd"); #endif if (hmod==NULL) { --- 86,92 ---- if (pfnPyWinObject_AsRASEAPUSERIDENTITY == NULL) { #ifdef _DEBUG ! HMODULE hmod = GetModuleHandle(_T("win2kras_d.pyd")); #else ! HMODULE hmod = GetModuleHandle(_T("win2kras.pyd")); #endif if (hmod==NULL) { Index: win32pipe.i =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/win32pipe.i,v retrieving revision 1.18.2.1 retrieving revision 1.18.2.2 diff -C2 -d -r1.18.2.1 -r1.18.2.2 *** win32pipe.i 29 Aug 2008 04:59:27 -0000 1.18.2.1 --- win32pipe.i 27 Jan 2009 07:56:45 -0000 1.18.2.2 *************** *** 37,40 **** --- 37,62 ---- %} + %ifdef SWIG_PY2K + %{ + extern PyObject *PyPopen(PyObject *self, PyObject *args); + extern PyObject *PyPopen2(PyObject *self, PyObject *args); + extern PyObject *PyPopen3(PyObject *self, PyObject *args); + extern PyObject *PyPopen4(PyObject *self, PyObject *args); + + %} + // @pymeth popen|Version of popen that works in a GUI + %native(popen) PyPopen; + + // @pymeth popen2|Variation on popen - returns 2 pipes + %native(popen2) PyPopen2; + + // @pymeth popen3|Variation on popen - returns 3 pipes + %native(popen3) PyPopen3; + + // @pymeth popen4|Like popen2, but stdout/err are combined. + %native(popen4) PyPopen4; + + %endif // SWIG_PY2K + %native(GetNamedPipeHandleState) MyGetNamedPipeHandleState; Index: PyTime.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/PyTime.cpp,v retrieving revision 1.19.2.4 retrieving revision 1.19.2.5 diff -C2 -d -r1.19.2.4 -r1.19.2.5 *** PyTime.cpp 9 Jan 2009 01:28:43 -0000 1.19.2.4 --- PyTime.cpp 27 Jan 2009 07:56:45 -0000 1.19.2.5 *************** *** 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[] = { *************** *** 273,277 **** if (!_tcsftime(szBuffer, 256/*_countof()*/, fmt, &tm)) szBuffer[0] = '\0'; // Better error? ! PyObject *rc = PyWinObject_FromTCHAR(szBuffer); if (bFreeString) PyWinObject_FreeTCHAR(fmt); return rc; --- 202,206 ---- if (!_tcsftime(szBuffer, 256/*_countof()*/, fmt, &tm)) szBuffer[0] = '\0'; // Better error? ! PyObject *rc = PyWinCoreString_FromString(szBuffer); if (bFreeString) PyWinObject_FreeTCHAR(fmt); return rc; *************** *** 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: PyWinTypesmodule.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/PyWinTypesmodule.cpp,v retrieving revision 1.39.2.12 retrieving revision 1.39.2.13 diff -C2 -d -r1.39.2.12 -r1.39.2.13 *** PyWinTypesmodule.cpp 8 Jan 2009 03:45:50 -0000 1.39.2.12 --- PyWinTypesmodule.cpp 27 Jan 2009 07:56:45 -0000 1.39.2.13 *************** *** 956,959 **** --- 956,961 ---- return -1; + if (!_PyWinDateTime_Init()) + return -1; return 0; } |
From: Mark H. <mha...@us...> - 2009-01-27 07:55:37
|
Update of /cvsroot/pywin32/pywin32/win32/test In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv18841/win32/test Modified Files: Tag: py3k test_win32api.py test_win32file.py Log Message: merge datetime changes from trunk (and other misc trunk changes) Index: test_win32file.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_win32file.py,v retrieving revision 1.13.2.7 retrieving revision 1.13.2.8 diff -C2 -d -r1.13.2.7 -r1.13.2.8 *** test_win32file.py 14 Jan 2009 12:42:03 -0000 1.13.2.7 --- test_win32file.py 27 Jan 2009 07:55:32 -0000 1.13.2.8 *************** *** 3,6 **** --- 3,7 ---- import win32api, win32file, win32pipe, pywintypes, winerror, win32event import win32con, ntsecuritycon + import win32timezone import sys import os *************** *** 11,14 **** --- 12,16 ---- import socket import datetime + import random try: *************** *** 121,128 **** os.unlink(filename) def testFileTimes(self): if issubclass(pywintypes.TimeType, datetime.datetime): ! from win32timezone import GetLocalTimeZone ! now = datetime.datetime.now(tz=GetLocalTimeZone()) nowish = now + datetime.timedelta(seconds=1) later = now + datetime.timedelta(seconds=120) --- 123,157 ---- 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): ! from win32timezone import TimeZoneInfo ! now = datetime.datetime.now(tz=TimeZoneInfo.local()) nowish = now + datetime.timedelta(seconds=1) later = now + datetime.timedelta(seconds=120) *************** *** 297,301 **** raise finally: ! handle.Close() t.join(3) self.failIf(t.isAlive(), "thread didn't finish") --- 326,331 ---- raise finally: ! if not test_overlapped_death: ! handle.Close() t.join(3) self.failIf(t.isAlive(), "thread didn't finish") *************** *** 556,559 **** --- 586,708 ---- 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(str2bytes('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, str2bytes("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, str2bytes('some expected response')) + self.assertEqual(self.request, str2bytes('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(str2bytes('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, str2bytes('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 + aaa = str2bytes("[AAA]") + bbb = str2bytes("[BBB]") + ccc = str2bytes("[CCC]") + ddd = str2bytes("[DDD]") + empty = str2bytes("") + 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, 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) + + if __name__ == '__main__': unittest.main() Index: test_win32api.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_win32api.py,v retrieving revision 1.13.2.4 retrieving revision 1.13.2.5 diff -C2 -d -r1.13.2.4 -r1.13.2.5 *** test_win32api.py 7 Jan 2009 06:25:16 -0000 1.13.2.4 --- test_win32api.py 27 Jan 2009 07:55:32 -0000 1.13.2.5 *************** *** 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 *************** *** 116,120 **** self.failUnlessEqual(long_name, win32api.GetLongPathNameW(short_name)) long_name = win32api.GetLongPathNameW(short_name) ! ## self.failUnless(type(long_name)==unicode, "GetLongPathNameW returned type '%s'" % (type(long_name),)) self.failUnless(long_name==fname, \ "Expected long name ('%s') to be original name ('%s')" % (long_name, fname)) --- 118,122 ---- self.failUnlessEqual(long_name, win32api.GetLongPathNameW(short_name)) long_name = win32api.GetLongPathNameW(short_name) ! self.failUnless(type(long_name)==str, "GetLongPathNameW returned type '%s'" % (type(long_name),)) self.failUnless(long_name==fname, \ "Expected long name ('%s') to be original name ('%s')" % (long_name, fname)) *************** *** 127,132 **** fname = os.path.abspath(me) # passing unicode should cause GetShortPathNameW to be called. ! short_name = win32api.GetShortPathName(fname) ! ## self.failUnless(isinstance(short_name, unicode)) long_name = win32api.GetLongPathName(short_name) self.failUnless(long_name==fname, \ --- 129,134 ---- fname = os.path.abspath(me) # passing unicode should cause GetShortPathNameW to be called. ! short_name = win32api.GetShortPathName(str(fname)) ! self.failUnless(isinstance(short_name, str)) long_name = win32api.GetLongPathName(short_name) self.failUnless(long_name==fname, \ *************** *** 134,138 **** self.failUnlessEqual(long_name, win32api.GetLongPathNameW(short_name)) long_name = win32api.GetLongPathNameW(short_name) ! ## self.failUnless(type(long_name)==unicode, "GetLongPathNameW returned type '%s'" % (type(long_name),)) self.failUnless(long_name==fname, \ "Expected long name ('%s') to be original name ('%s')" % (long_name, fname)) --- 136,140 ---- self.failUnlessEqual(long_name, win32api.GetLongPathNameW(short_name)) long_name = win32api.GetLongPathNameW(short_name) ! self.failUnless(type(long_name)==str, "GetLongPathNameW returned type '%s'" % (type(long_name),)) self.failUnless(long_name==fname, \ "Expected long name ('%s') to be original name ('%s')" % (long_name, fname)) *************** *** 162,166 **** raise ! attr = win32api.GetFileAttributes(fname) self.failUnless(attr & win32con.FILE_ATTRIBUTE_DIRECTORY, attr) --- 164,168 ---- raise ! attr = win32api.GetFileAttributes(str(fname)) self.failUnless(attr & win32con.FILE_ATTRIBUTE_DIRECTORY, attr) |
From: Mark H. <mha...@us...> - 2009-01-27 07:55:37
|
Update of /cvsroot/pywin32/pywin32/win32/src In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv18841/win32/src Modified Files: Tag: py3k PyWinTypes.h win32file.i Log Message: merge datetime changes from trunk (and other misc trunk changes) Index: PyWinTypes.h =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/PyWinTypes.h,v retrieving revision 1.51.2.9 retrieving revision 1.51.2.10 diff -C2 -d -r1.51.2.9 -r1.51.2.10 *** PyWinTypes.h 8 Jan 2009 03:45:50 -0000 1.51.2.9 --- PyWinTypes.h 27 Jan 2009 07:55:31 -0000 1.51.2.10 *************** *** 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.93.2.6 retrieving revision 1.93.2.7 diff -C2 -d -r1.93.2.6 -r1.93.2.7 *** win32file.i 3 Jan 2009 23:46:35 -0000 1.93.2.6 --- win32file.i 27 Jan 2009 07:55:31 -0000 1.93.2.7 *************** *** 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 *************** *** 342,346 **** // @pyparm <o PyUnicode>|fileName||The filename to delete - %{ // @pyswig str/buffer|DeviceIoControl|Sends a control code to a device or file system driver --- 347,350 ---- *************** *** 669,679 **** BOOLAPI GetFileTime( HANDLE handle, // @pyparm <o PyHANDLE>|handle||Handle to the file. ! FILETIME *OUTPUT, ! FILETIME *OUTPUT, ! FILETIME *OUTPUT ); %{ // @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) --- 673,693 ---- BOOLAPI GetFileTime( HANDLE handle, // @pyparm <o PyHANDLE>|handle||Handle to the file. ! FILETIME *OUTPUT, // @pyparm <o PyTime>|creationTime|| ! FILETIME *OUTPUT, // @pyparm <o PyTime>|accessTime|| ! FILETIME *OUTPUT // @pyparm <o PyTime>|writeTime|| ); %{ + // 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) *************** *** 701,705 **** 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; } *************** *** 710,714 **** 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; } *************** *** 719,723 **** 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; } *************** *** 1659,1663 **** DWORD flags, bytes_to_write, bytes_per_send; OVERLAPPED *pOverlapped; ! int error, rc; static char *keywords[]={"Socket","File","NumberOfBytesToWrite", "NumberOfBytesPerSend", --- 1685,1689 ---- DWORD flags, bytes_to_write, bytes_per_send; OVERLAPPED *pOverlapped; ! int error, rc; static char *keywords[]={"Socket","File","NumberOfBytesToWrite", "NumberOfBytesPerSend", *************** *** 1699,1708 **** 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; --- 1725,1734 ---- 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; *************** *** 1710,1714 **** rc = WSAGetLastError(); Py_END_ALLOW_THREADS; ! if (rc == 0 || rc == ERROR_IO_PENDING || rc == WSA_IO_PENDING) return PyInt_FromLong(rc); --- 1736,1740 ---- rc = WSAGetLastError(); Py_END_ALLOW_THREADS; ! if (rc == 0 || rc == ERROR_IO_PENDING || rc == WSA_IO_PENDING) return PyInt_FromLong(rc); *************** *** 1735,1739 **** 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, --- 1761,1765 ---- 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, *************** *** 1762,1766 **** } // convert the address ! // char pbuf[30]; char *hptr, *pptr; --- 1788,1792 ---- } // convert the address ! // char pbuf[30]; char *hptr, *pptr; *************** *** 1810,1819 **** } // done screwing with the address ! if (!PyWinObject_AsOVERLAPPED(obOverlapped, &pOverlapped)) { return NULL; } ! rc=0; Py_BEGIN_ALLOW_THREADS; --- 1836,1845 ---- } // done screwing with the address ! if (!PyWinObject_AsOVERLAPPED(obOverlapped, &pOverlapped)) { return NULL; } ! rc=0; Py_BEGIN_ALLOW_THREADS; *************** *** 5241,5244 **** --- 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-27 07:55:37
|
Update of /cvsroot/pywin32/pywin32/win32/Lib In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv18841/win32/Lib Modified Files: Tag: py3k win32timezone.py Log Message: merge datetime changes from trunk (and other misc trunk changes) Index: win32timezone.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/Lib/win32timezone.py,v retrieving revision 1.9.2.9 retrieving revision 1.9.2.10 diff -C2 -d -r1.9.2.9 -r1.9.2.10 *** win32timezone.py 8 Jan 2009 03:45:50 -0000 1.9.2.9 --- win32timezone.py 27 Jan 2009 07:55:31 -0000 1.9.2.10 *************** *** 13,17 **** Written by Jason R. Coombs (ja...@ja...). ! Copyright © 2003-2008. All Rights Reserved. --- 13,17 ---- Written by Jason R. Coombs (ja...@ja...). ! Copyright © 2003-2009. All Rights Reserved. *************** *** 24,29 **** >>> import win32timezone, datetime >>> assert 'Mountain Standard Time' in win32timezone.TimeZoneInfo.get_sorted_time_zone_names() ! >>> tzi = win32timezone.TimeZoneInfo('Mountain Standard Time') ! >>> now = datetime.datetime.now(tzi) The now object is now a time-zone aware object, and daylight savings- --- 24,29 ---- >>> import win32timezone, datetime >>> assert 'Mountain Standard Time' in win32timezone.TimeZoneInfo.get_sorted_time_zone_names() ! >>> MST = win32timezone.TimeZoneInfo('Mountain Standard Time') ! >>> now = datetime.datetime.now(MST) The now object is now a time-zone aware object, and daylight savings- *************** *** 40,47 **** datetime.timedelta(-1, 61200) ! >>> aug2 = datetime.datetime(2003, 8, 2, tzinfo = tzi) >>> tuple(aug2.utctimetuple()) (2003, 8, 2, 6, 0, 0, 5, 214, 0) ! >>> nov2 = datetime.datetime(2003, 11, 25, tzinfo = tzi) >>> tuple(nov2.utctimetuple()) (2003, 11, 25, 7, 0, 0, 1, 329, 0) --- 40,47 ---- datetime.timedelta(-1, 61200) ! >>> aug2 = datetime.datetime(2003, 8, 2, tzinfo = MST) >>> tuple(aug2.utctimetuple()) (2003, 8, 2, 6, 0, 0, 5, 214, 0) ! >>> nov2 = datetime.datetime(2003, 11, 25, tzinfo = MST) >>> tuple(nov2.utctimetuple()) (2003, 11, 25, 7, 0, 0, 1, 329, 0) *************** *** 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, *************** *** 78,81 **** --- 78,87 ---- True + It's possible to construct a TimeZoneInfo from a TimeZoneDescription + including the currently-defined zone. + >>> tz = win32timezone.TimeZoneInfo(TimeZoneDefinition.current()) + >>> tz == pickle.loads(pickle.dumps(tz)) + True + >>> aest = win32timezone.TimeZoneInfo('AUS Eastern Standard Time') >>> est = win32timezone.TimeZoneInfo('E. Australia Standard Time') *************** *** 98,113 **** http://support.microsoft.com/gp/cp_dst) ! As a result, the following test will fail in machines with the patch ! except for Vista and its succssors, which have dynamic time ! zone support. ! #>>> nov2 = datetime.datetime(2003, 11, 2, tzinfo = tzi) ! #>>> nov2.utctimetuple() ! (2003, 11, 2, 7, 0, 0, 6, 306, 0) - Note that is the correct response beginning in 2007 - This test will fail in Windows versions prior to Vista - #>>> nov2 = datetime.datetime(2007, 11, 2, tzinfo = tzi) - #>>> nov2.utctimetuple() - (2007, 11, 2, 6, 0, 0, 4, 306, 0) There is a function you can call to get some capabilities of the time --- 104,126 ---- http://support.microsoft.com/gp/cp_dst) ! As a result, patched systems will give an incorrect result for ! dates prior to the designated year except for Vista and its ! successors, which have dynamic time zone support. ! >>> nov2_pre_change = datetime.datetime(2003, 11, 2, tzinfo = MST) ! >>> old_response = (2003, 11, 2, 7, 0, 0, 6, 306, 0) ! >>> incorrect_patch_response = (2003, 11, 2, 6, 0, 0, 6, 306, 0) ! >>> pre_response = nov2_pre_change.utctimetuple() ! >>> pre_response in (old_response, incorrect_patch_response) ! True ! ! Furthermore, unpatched systems pre-Vista will give an incorrect ! result for dates after 2007. ! >>> nov2_post_change = datetime.datetime(2007, 11, 2, tzinfo = MST) ! >>> incorrect_unpatched_response = (2007, 11, 2, 7, 0, 0, 4, 306, 0) ! >>> new_response = (2007, 11, 2, 6, 0, 0, 4, 306, 0) ! >>> post_response = nov2_post_change.utctimetuple() ! >>> post_response in (new_response, incorrect_unpatched_response) ! True There is a function you can call to get some capabilities of the time *************** *** 120,123 **** --- 133,149 ---- >>> 'DynamicTZSupport' in caps True + + >>> both_dates_correct = (pre_response == old_response and post_response == new_response) + >>> old_dates_wrong = (pre_response == incorrect_patch_response) + >>> new_dates_wrong = (post_response == incorrect_unpatched_response) + + >>> caps['DynamicTZSupport'] == both_dates_correct + True + + >>> (not caps['DynamicTZSupport'] and caps['MissingTZPatch']) == new_dates_wrong + True + + >>> (not caps['DynamicTZSupport'] and not caps['MissingTZPatch']) == old_dates_wrong + True """ from __future__ import generators *************** *** 137,195 **** import operator import warnings import logging log = logging.getLogger(__file__) ! class WinTZI(object): ! format = '3l8h8h' ! def __init__(self, key, name = None): ! if(not name and len(key) == struct.calcsize(self.format)): ! self.__init_from_bytes__(key) ! else: ! self.__init_from_reg_key__(key, name) ! ! def __init_from_reg_key__(self, key, name = None): ! if not name: ! key, name = os.path.split(key) ! value, type = winreg.QueryValueEx(key, name) ! self.__init_from_bytes__(value) ! ! def __init_from_bytes__(self, bytes): ! components = struct.unpack(self.format, bytes) ! makeMinuteTimeDelta = lambda x: datetime.timedelta(minutes = x) ! self.bias, self.standardBiasOffset, self.daylightBiasOffset = \ ! map(makeMinuteTimeDelta, components[:3]) ! # daylightEnd and daylightStart are 8-tuples representing a Win32 SYSTEMTIME structure ! self.daylightEnd, self.daylightStart = components[3:11], components[11:19] ! def LocateStartDay(self, year): ! return self._LocateDay(year, self.daylightStart) ! def LocateEndDay(self, year): ! return self._LocateDay(year, self.daylightEnd) ! def _LocateDay(self, year, win32SystemTime): """ ! Takes a SYSTEMTIME structure as retrieved from a TIME_ZONE_INFORMATION ! structure and interprets it based on the given year to identify the actual day. This method is necessary because the SYSTEMTIME structure refers to a day by its ! day of the week or week of the month (e.g. 4th saturday in April). ! Refer to the Windows Platform SDK for more information on the SYSTEMTIME ! and TIME_ZONE_INFORMATION structures. """ - month = win32SystemTime[1] # MS stores Sunday as 0, Python datetime stores Monday as zero ! targetWeekday = (win32SystemTime[2] + 6) % 7 ! # win32SystemTime[3] is the week of the month, so the following ! # is the first day of that week ! day = (win32SystemTime[3] - 1) * 7 + 1 ! hour, min, sec, msec = win32SystemTime[4:] ! result = datetime.datetime(year, month, day, hour, min, sec, msec) # now the result is the correct week, but not necessarily the correct day of the week ! daysToGo = targetWeekday - result.weekday() ! result += datetime.timedelta(daysToGo) # if we selected a day in the month following the target month, # move back a week or two. --- 163,358 ---- import operator import warnings + import pywintypes + from itertools import count import logging 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), ! ] ! ! ! class TimeZoneDefinition(DYNAMIC_TIME_ZONE_INFORMATION): ! """ ! A time zone definition class based on the win32 ! DYNAMIC_TIME_ZONE_INFORMATION structure. ! ! Describes a bias against UTC (bias), and two dates at which a separate ! additional bias applies (standard_bias and daylight_bias). ! """ ! ! def __init__(self, *args, **kwargs): """ ! Try to construct a TimeZoneDefinition from ! a) [DYNAMIC_]TIME_ZONE_INFORMATION args ! b) another TimeZoneDefinition ! c) a byte structure (using _from_bytes) ! """ ! try: ! super(TimeZoneDefinition, self).__init__(*args, **kwargs) ! return ! except (TypeError, ValueError): ! pass ! ! try: ! self.__init_from_other(*args, **kwargs) ! return ! except TypeError: ! pass ! ! try: ! self.__init_from_bytes(*args, **kwargs) ! return ! except TypeError: ! pass ! ! raise TypeError("Invalid arguments for %s" % self.__class__) ! ! def __init_from_bytes(self, bytes, standard_name='', daylight_name='', key_name='', daylight_disabled=False): ! format = '3l8h8h' ! components = struct.unpack(format, bytes) ! bias, standard_bias, daylight_bias = components[:3] ! standard_start = SYSTEMTIME(*components[3:11]) ! daylight_start = SYSTEMTIME(*components[11:19]) ! super(TimeZoneDefinition, self).__init__(bias, ! standard_name, standard_start, standard_bias, ! daylight_name, daylight_start, daylight_bias, ! key_name, daylight_disabled,) ! ! def __init_from_other(self, other): ! if not isinstance(other, TIME_ZONE_INFORMATION): ! raise TypeError("Not a TIME_ZONE_INFORMATION") ! for name in other.field_names(): ! # explicitly get the value from the underlying structure ! value = super(TimeZoneDefinition, other).__getattribute__(other, name) ! setattr(self, name, value) ! # consider instead of the loop above just copying the memory directly ! #size = max(ctypes.sizeof(DYNAMIC_TIME_ZONE_INFO), ctypes.sizeof(other)) ! #ctypes.memmove(ctypes.addressof(self), other, size) ! ! 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 ! ! @classmethod ! 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) ! ! def locate_daylight_start(self, year): ! return self._locate_day(year, self.daylight_start) ! ! def locate_standard_start(self, year): ! return self._locate_day(year, self.standard_start) ! ! @staticmethod ! def _locate_day(year, cutoff): ! """ ! Takes a SYSTEMTIME object, such as retrieved from a TIME_ZONE_INFORMATION ! structure or call to GetTimeZoneInformation and interprets it based on the given ! year to identify the actual day. This method is necessary because the SYSTEMTIME structure refers to a day by its ! day of the week and week of the month (e.g. 4th saturday in March). ! >>> SATURDAY = 6 ! >>> MARCH = 3 ! >>> st = SYSTEMTIME(2000, MARCH, SATURDAY, 4, 0, 0, 0, 0) ! ! # according to my calendar, the 4th Saturday in March in 2009 was the 28th ! >>> expected_date = datetime.datetime(2009, 3, 28) ! >>> TimeZoneDefinition._locate_day(2009, st) == expected_date ! True """ # MS stores Sunday as 0, Python datetime stores Monday as zero ! target_weekday = (cutoff.day_of_week + 6) % 7 ! # For SYSTEMTIMEs relating to time zone inforamtion, cutoff.day ! # is the week of the month ! week_of_month = cutoff.day ! # so the following is the first day of that week ! day = (week_of_month - 1) * 7 + 1 ! result = datetime.datetime(year, cutoff.month, day, ! cutoff.hour, cutoff.minute, cutoff.second, cutoff.millisecond) # now the result is the correct week, but not necessarily the correct day of the week ! days_to_go = (target_weekday - result.weekday()) % 7 ! result += datetime.timedelta(days_to_go) # if we selected a day in the month following the target month, # move back a week or two. *************** *** 197,224 **** # to be the last week in a month and adding the time delta might have # pushed the result into the next month. ! while result.month == month + 1: result -= datetime.timedelta(weeks = 1) return result - def __cmp__(self, other): - return cmp(self.__dict__, other.__dict__) - class TimeZoneInfo(datetime.tzinfo): """ ! Main class for handling win32 time zones. Usage: TimeZoneInfo(<Time Zone Standard Name>, [<Fix Standard Time>]) ! If <Fix Standard Time> evaluates to True, daylight savings time is calculated in the same ! way as standard time. """ # this key works for WinNT+, but not for the Win95 line. tzRegKey = r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones' ! ! def __init__(self, timeZoneName, fixedStandardTime=False): ! self.timeZoneName = timeZoneName ! key = self._FindTimeZoneKey() ! self._LoadInfoFromKey(key) ! self.fixedStandardTime = fixedStandardTime def _FindTimeZoneKey(self): --- 360,388 ---- # to be the last week in a month and adding the time delta might have # pushed the result into the next month. ! while result.month == cutoff.month + 1: result -= datetime.timedelta(weeks = 1) return result class TimeZoneInfo(datetime.tzinfo): """ ! Main class for handling Windows time zones. Usage: TimeZoneInfo(<Time Zone Standard Name>, [<Fix Standard Time>]) ! ! If <Fix Standard Time> evaluates to True, daylight savings time is ! calculated in the same ! way as standard time. """ # 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): ! self._LoadFromTZI(param) ! if isinstance(param, str): ! self.timeZoneName = param ! self._LoadInfoFromKey() ! self.fixedStandardTime = fix_standard_time def _FindTimeZoneKey(self): *************** *** 230,262 **** # English-based hard-coded time zones. timeZoneName = zoneNames.get(self.timeZoneName, self.timeZoneName) ! tzRegKeyPath = os.path.join(self.tzRegKey, timeZoneName) try: ! key = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, tzRegKeyPath) except: raise ValueError('Timezone Name %s not found.' % timeZoneName) ! return key ! ! def __getinitargs__(self): ! return (self.timeZoneName,) ! def _LoadInfoFromKey(self, key): """Loads the information from an opened time zone registry key into relevant fields of this TZI object""" ! self.displayName = winreg.QueryValueEx(key, "Display")[0] ! self.standardName = winreg.QueryValueEx(key, "Std")[0] ! self.daylightName = winreg.QueryValueEx(key, "Dlt")[0] ! self.staticInfo = WinTZI(key, "TZI") self._LoadDynamicInfoFromKey(key) def _LoadDynamicInfoFromKey(self, key): try: ! dkey = winreg.OpenKeyEx(key, 'Dynamic DST') except WindowsError: return - info = _RegKeyDict(dkey) del info['FirstEntry'] del info['LastEntry'] years = map(int, list(info.keys())) ! values = map(WinTZI, list(info.values())) # create a range mapping that searches by descending year and matches # if the target year is greater or equal. --- 394,430 ---- # English-based hard-coded time zones. timeZoneName = zoneNames.get(self.timeZoneName, self.timeZoneName) ! key = _RegKeyDict.open(winreg.HKEY_LOCAL_MACHINE, self.tzRegKey) try: ! result = key.subkey(timeZoneName) except: raise ValueError('Timezone Name %s not found.' % timeZoneName) ! return result ! def _LoadInfoFromKey(self): """Loads the information from an opened time zone registry key into relevant fields of this TZI object""" ! key = self._FindTimeZoneKey() ! self.displayName = key['Display'] ! self.standardName = key['Std'] ! self.daylightName = key['Dlt'] ! self.staticInfo = TimeZoneDefinition(key['TZI']) self._LoadDynamicInfoFromKey(key) + def _LoadFromTZI(self, tzi): + self.timeZoneName = tzi.standard_name + self.displayName = 'Unknown' + self.standardName = tzi.standard_name + self.daylightName = tzi.daylight_name + self.staticInfo = tzi + def _LoadDynamicInfoFromKey(self, key): try: ! info = key.subkey('Dynamic DST') except WindowsError: return del info['FirstEntry'] del info['LastEntry'] years = map(int, list(info.keys())) ! values = map(TimeZoneDefinition, list(info.values())) # create a range mapping that searches by descending year and matches # if the target year is greater or equal. *************** *** 275,281 **** def tzname(self, dt): winInfo = self.getWinInfo(dt) ! if self.dst(dt) == winInfo.daylightBiasOffset: result = self.daylightName ! elif self.dst(dt) == winInfo.standardBiasOffset: result = self.standardName return result --- 443,449 ---- def tzname(self, dt): winInfo = self.getWinInfo(dt) ! if self.dst(dt) == winInfo.daylight_bias: result = self.daylightName ! elif self.dst(dt) == winInfo.standard_bias: result = self.standardName return result *************** *** 291,299 **** def _getStandardBias(self, dt): winInfo = self.getWinInfo(dt.year) ! return winInfo.bias + winInfo.standardBiasOffset def _getDaylightBias(self, dt): winInfo = self.getWinInfo(dt.year) ! return winInfo.bias + winInfo.daylightBiasOffset def utcoffset(self, dt): --- 459,467 ---- def _getStandardBias(self, dt): winInfo = self.getWinInfo(dt.year) ! return winInfo.bias + winInfo.standard_bias def _getDaylightBias(self, dt): winInfo = self.getWinInfo(dt.year) ! return winInfo.bias + winInfo.daylight_bias def utcoffset(self, dt): *************** *** 310,316 **** winInfo = self.getWinInfo(dt.year) if not self.fixedStandardTime and self._inDaylightSavings(dt): ! result = winInfo.daylightBiasOffset else: ! result = winInfo.standardBiasOffset return result --- 478,484 ---- winInfo = self.getWinInfo(dt.year) if not self.fixedStandardTime and self._inDaylightSavings(dt): ! result = winInfo.daylight_bias else: ! result = winInfo.standard_bias return result *************** *** 335,385 **** def GetDSTStartTime(self, year): "Given a year, determines the time when daylight savings time starts" ! return self.getWinInfo(year).LocateStartDay(year) def GetDSTEndTime(self, year): "Given a year, determines the time when daylight savings ends." ! return self.getWinInfo(year).LocateEndDay(year) def __cmp__(self, other): return cmp(self.__dict__, other.__dict__) # helper methods for accessing the timezone info from the registry def _get_time_zone_key(subkey=None): "Return the registry key that stores time zone details" ! key = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, TimeZoneInfo.tzRegKey) if subkey: ! key = winreg.OpenKeyEx(key, subkey) return key - _get_time_zone_key = staticmethod(_get_time_zone_key) def _get_time_zone_key_names(): "Returns the names of the (registry keys of the) time zones" ! return _RegKeyEnumerator(TimeZoneInfo._get_time_zone_key()) ! _get_time_zone_key_names = staticmethod(_get_time_zone_key_names) ! def _get_indexed_time_zone_keys(index_key='Index'): """ Get the names of the registry keys indexed by a value in that key. """ ! key_names = tuple(TimeZoneInfo._get_time_zone_key_names()) def get_index_value(key_name): key = TimeZoneInfo._get_time_zone_key(key_name) ! value, type = winreg.QueryValueEx(key, index_key) ! return value values = map(get_index_value, key_names) return zip(values, key_names) - _get_indexed_time_zone_keys = staticmethod(_get_indexed_time_zone_keys) def get_sorted_time_zone_names(): "Return a list of time zone names that can be used to initialize TimeZoneInfo instances" tzs = TimeZoneInfo.get_sorted_time_zones() get_standard_name = lambda tzi: tzi.standardName ! return map(get_standard_name, tzs) ! get_sorted_time_zone_names = staticmethod(get_sorted_time_zone_names) def get_all_time_zones(): return [TimeZoneInfo(n) for n in TimeZoneInfo._get_time_zone_key_names()] - get_all_time_zones = staticmethod(get_all_time_zones) def get_sorted_time_zones(key=None): """ --- 503,600 ---- def GetDSTStartTime(self, year): "Given a year, determines the time when daylight savings time starts" ! return self.getWinInfo(year).locate_daylight_start(year) def GetDSTEndTime(self, year): "Given a year, determines the time when daylight savings ends." ! return self.getWinInfo(year).locate_standard_start(year) def __cmp__(self, other): 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_): + """Returns the local time zone as defined by the operating system in the + registry. + >>> localTZ = TimeZoneInfo.local() + >>> now_local = datetime.datetime.now(localTZ) + >>> now_UTC = datetime.datetime.utcnow() + >>> (now_UTC - now_local) < datetime.timedelta(seconds = 5) + Traceback (most recent call last): + ... + TypeError: can't subtract offset-naive and offset-aware datetimes + + >>> now_UTC = now_UTC.replace(tzinfo = TimeZoneInfo('GMT Standard Time', True)) + + Now one can compare the results of the two offset aware values + >>> (now_UTC - now_local) < datetime.timedelta(seconds = 5) + True + """ + code, info = TimeZoneDefinition.current() + # code is 0 if daylight savings is disabled or not defined + # code is 1 or 2 if daylight savings is enabled, 2 if currently active + fix_standard_time = not code + # note that although the given information is sufficient to construct a WinTZI object, it's + # not sufficient to represent the time zone in which the current user is operating due + # to dynamic time zones. + return class_(info, fix_standard_time) + + @classmethod + def utc(class_): + """Returns a time-zone representing UTC. + + Same as TimeZoneInfo('GMT Standard Time', True) but caches the result + for performance. + + >>> isinstance(TimeZoneInfo.utc(), TimeZoneInfo) + True + """ + if not '_tzutc' in class_.__dict__: + setattr(class_, '_tzutc', class_('GMT Standard Time', True)) + return class_._tzutc + # helper methods for accessing the timezone info from the registry + @staticmethod def _get_time_zone_key(subkey=None): "Return the registry key that stores time zone details" ! key = _RegKeyDict.open(winreg.HKEY_LOCAL_MACHINE, TimeZoneInfo.tzRegKey) if subkey: ! key = key.subkey(subkey) return key + @staticmethod def _get_time_zone_key_names(): "Returns the names of the (registry keys of the) time zones" ! return TimeZoneInfo._get_time_zone_key().subkeys() ! ! @staticmethod def _get_indexed_time_zone_keys(index_key='Index'): """ 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) ! return key[index_key] values = map(get_index_value, key_names) return zip(values, key_names) + @staticmethod def get_sorted_time_zone_names(): "Return a list of time zone names that can be used to initialize TimeZoneInfo instances" 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 def get_sorted_time_zones(key=None): """ *************** *** 394,419 **** zones.sort(key=key) return zones - get_sorted_time_zones = staticmethod(get_sorted_time_zones) - - def _RegKeyEnumerator(key): - return _RegEnumerator(key, winreg.EnumKey) ! def _RegValueEnumerator(key): ! return _RegEnumerator(key, winreg.EnumValue) ! ! def _RegEnumerator(key, func): ! "Enumerates an open registry key as an iterable generator" ! index = 0 ! try: ! while 1: ! yield func(key, index) ! index += 1 ! except WindowsError: pass ! def _RegKeyDict(key): ! values = _RegValueEnumerator(key) ! values = tuple(values) ! return dict([(name, value) for name,value,type in values]) # for backward compatibility def deprecated(func, name='Unknown'): --- 609,650 ---- zones.sort(key=key) return zones ! class _RegKeyDict(dict): ! def __init__(self, key): ! dict.__init__(self) ! self.key = key ! self.__load_values() ! @classmethod ! def open(cls, *args, **kargs): ! return _RegKeyDict(winreg.OpenKeyEx(*args, **kargs)) ! ! def subkey(self, name): ! return _RegKeyDict(winreg.OpenKeyEx(self.key, name)) ! ! def __load_values(self): ! pairs = [(n, v) for (n, v, t) in self._enumerate_reg_values(self.key)] ! self.update(pairs) ! ! def subkeys(self): ! return self._enumerate_reg_keys(self.key) + @staticmethod + def _enumerate_reg_values(key): + return _RegKeyDict._enumerate_reg(key, winreg.EnumValue) + + @staticmethod + def _enumerate_reg_keys(key): + return _RegKeyDict._enumerate_reg(key, winreg.EnumKey) + + @staticmethod + def _enumerate_reg(key, func): + "Enumerates an open registry key as an iterable generator" + try: + for index in count(): + yield func(key, index) + except WindowsError: pass + + # for backward compatibility def deprecated(func, name='Unknown'): *************** *** 435,482 **** # end backward compatibility ! def GetLocalTimeZone(): ! """Returns the local time zone as defined by the operating system in the ! registry. ! Note that this will only work if the TimeZone in the registry has not been ! customized. It should have been selected from the Windows interface. ! >>> localTZ = GetLocalTimeZone() ! >>> nowLoc = datetime.datetime.now(localTZ) ! >>> nowUTC = datetime.datetime.utcnow() ! >>> (nowUTC - nowLoc) < datetime.timedelta(seconds = 5) ! Traceback (most recent call last): ! ... ! TypeError: can't subtract offset-naive and offset-aware datetimes ! ! >>> nowUTC = nowUTC.replace(tzinfo = TimeZoneInfo('GMT Standard Time', True)) ! ! Now one can compare the results of the two offset aware values ! >>> (nowUTC - nowLoc) < datetime.timedelta(seconds = 5) ! True """ ! tzRegKey = r'SYSTEM\CurrentControlSet\Control\TimeZoneInformation' ! key = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, tzRegKey) ! local = _RegKeyDict(key) ! # if the user has not checked "Automatically adjust clock for daylight ! # saving changes" in the Date and Time Properties control, the standard ! # and daylight values will be the same. If this is the case, create a ! # timezone object fixed to standard time. ! fixStandardTime = local['StandardName'] == local['DaylightName'] and \ ! local['StandardBias'] == local['DaylightBias'] ! keyName = ['StandardName', 'TimeZoneKeyName'][sys.getwindowsversion() >= (6,)] ! standardName = local[keyName] ! standardName = __TimeZoneKeyNameWorkaround(standardName) ! return TimeZoneInfo(standardName, fixStandardTime) ! def __TimeZoneKeyNameWorkaround(name): ! """It may be a bug in Vista, but in standard Windows Vista install ! (both 32-bit and 64-bit), it appears the TimeZoneKeyName returns a ! string with extraneous characters. ! >>> __TimeZoneKeyNameWorkaround("foo\\0xxx") ! 'foo' ! >>> __TimeZoneKeyNameWorkaround("foo") ! 'foo' """ ! # remove anything after and including the first null character. ! return name.split('\x00',1)[0] def GetTZCapabilities(): --- 666,686 ---- # end backward compatibility ! def utcnow(): """ ! Return the UTC time now with timezone awareness as enabled ! by this module ! >>> now = utcnow() ! """ ! now = datetime.datetime.utcnow() ! now = now.replace(tzinfo=TimeZoneInfo.utc()) ! return now ! def now(): """ ! Return the local time now with timezone awareness as enabled ! by this module ! >>> now_local = now() ! """ ! return datetime.datetime.now(TimeZoneInfo.local()) def GetTZCapabilities(): *************** *** 504,510 **** def resolveMUITimeZone(spec): """Resolve a multilingual user interface resource for the time zone name >>> result = resolveMUITimeZone('@tzres.dll,-110') ! >>> str_type = type(''.encode('ascii').decode('ascii')) # 2to3 doesn't do docstrings yet! ! >>> expectedResultType = [type(None),str_type][sys.getwindowsversion() >= (6,)] >>> type(result) is expectedResultType True --- 708,717 ---- 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,)] >>> type(result) is expectedResultType True *************** *** 573,579 **** self.match = keyMatchComparator ! def __getitem__(self, item): sortedKeys = list(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 = list(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]) *************** *** 587,591 **** 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] *************** *** 593,598 **** def bounds(self): ! sortedKeys = list(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-27 07:55:37
|
Update of /cvsroot/pywin32/pywin32/com/win32com/client In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv18841/com/win32com/client Modified Files: Tag: py3k build.py Log Message: merge datetime changes from trunk (and other misc trunk changes) Index: build.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/client/build.py,v retrieving revision 1.31.2.9 retrieving revision 1.31.2.10 diff -C2 -d -r1.31.2.9 -r1.31.2.10 *** build.py 25 Jan 2009 04:52:20 -0000 1.31.2.9 --- build.py 27 Jan 2009 07:55:31 -0000 1.31.2.10 *************** *** 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-27 07:55:36
|
Update of /cvsroot/pywin32/pywin32/com/win32com/test In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv18841/com/win32com/test Modified Files: Tag: py3k testPyComTest.py testShell.py Log Message: merge datetime changes from trunk (and other misc trunk changes) Index: testShell.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/test/testShell.py,v retrieving revision 1.10.4.6 retrieving revision 1.10.4.7 diff -C2 -d -r1.10.4.6 -r1.10.4.7 *** testShell.py 14 Jan 2009 12:42:02 -0000 1.10.4.6 --- testShell.py 27 Jan 2009 07:55:31 -0000 1.10.4.7 *************** *** 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="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="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.32.2.9 retrieving revision 1.32.2.10 diff -C2 -d -r1.32.2.9 -r1.32.2.10 *** testPyComTest.py 9 Jan 2009 01:26:19 -0000 1.32.2.9 --- testPyComTest.py 27 Jan 2009 07:55:31 -0000 1.32.2.10 *************** *** 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", "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", "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-27 07:48:54
|
Update of /cvsroot/pywin32/pywin32/com/win32com/server In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv15819/com/win32com/server Modified Files: Tag: py3k register.py Log Message: merge some 64bit changes from the trunk Index: register.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/server/register.py,v retrieving revision 1.21.2.3 retrieving revision 1.21.2.4 diff -C2 -d -r1.21.2.3 -r1.21.2.4 *** register.py 5 Jan 2009 12:51:26 -0000 1.21.2.3 --- register.py 27 Jan 2009 07:48:43 -0000 1.21.2.4 *************** *** 103,107 **** if not os.path.exists(exeName): # See if in our sys.prefix/pcbuild directory (for developers) ! exeName = os.path.join( sys.prefix, "PCbuild", exeBaseName ) if not os.path.exists(exeName): # See if the registry has some info. --- 103,110 ---- if not os.path.exists(exeName): # See if in our sys.prefix/pcbuild directory (for developers) ! if "64 bit" in sys.version: ! exeName = os.path.join( sys.prefix, "PCbuild", "amd64", exeBaseName ) ! else: ! exeName = os.path.join( sys.prefix, "PCbuild", exeBaseName ) if not os.path.exists(exeName): # See if the registry has some info. |
From: Mark H. <mha...@us...> - 2009-01-27 07:48:52
|
Update of /cvsroot/pywin32/pywin32/Pythonwin/pywin/framework In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv15819/Pythonwin/pywin/framework Modified Files: Tag: py3k mdi_pychecker.py Log Message: merge some 64bit changes from the trunk Index: mdi_pychecker.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/Pythonwin/pywin/framework/mdi_pychecker.py,v retrieving revision 1.2.2.3 retrieving revision 1.2.2.4 diff -C2 -d -r1.2.2.3 -r1.2.2.4 *** mdi_pychecker.py 27 Nov 2008 11:31:03 -0000 1.2.2.3 --- mdi_pychecker.py 27 Jan 2009 07:48:39 -0000 1.2.2.4 *************** *** 291,295 **** py = os.path.join(sys.prefix, 'python.exe') if not os.path.isfile(py): ! py = os.path.join(sys.prefix, 'PCBuild', 'python.exe') try: py = win32api.GetShortPathName(py) --- 291,298 ---- py = os.path.join(sys.prefix, 'python.exe') if not os.path.isfile(py): ! if "64 bit" in sys.version: ! py = os.path.join(sys.prefix, 'PCBuild', 'amd64', 'python.exe') ! else: ! py = os.path.join(sys.prefix, 'PCBuild', 'python.exe') try: py = win32api.GetShortPathName(py) |
From: Mark H. <mha...@us...> - 2009-01-27 07:48:49
|
Update of /cvsroot/pywin32/pywin32/win32/scripts In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv15819/win32/scripts Modified Files: Tag: py3k regsetup.py Log Message: merge some 64bit changes from the trunk Index: regsetup.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/scripts/regsetup.py,v retrieving revision 1.15.2.3 retrieving revision 1.15.2.4 diff -C2 -d -r1.15.2.3 -r1.15.2.4 *** regsetup.py 4 Dec 2008 05:08:41 -0000 1.15.2.3 --- regsetup.py 27 Jan 2009 07:48:44 -0000 1.15.2.4 *************** *** 113,117 **** found = os.path.join(sys.prefix, possibleRealNames) if not FileExists(found): # for developers ! found = os.path.join(sys.prefix, "PCBuild", possibleRealNames) if not FileExists(found): found = LocateFileName(possibleRealNames, searchPaths) --- 113,120 ---- found = os.path.join(sys.prefix, possibleRealNames) if not FileExists(found): # for developers ! if "64 bit" in sys.version: ! found = os.path.join(sys.prefix, "PCBuild", "amd64", possibleRealNames) ! else: ! found = os.path.join(sys.prefix, "PCBuild", possibleRealNames) if not FileExists(found): found = LocateFileName(possibleRealNames, searchPaths) *************** *** 342,345 **** --- 345,350 ---- # value check = os.path.join(sys.prefix, "PCBuild") + if "64 bit" in sys.version: + check = os.path.join(check, "amd64") if os.path.isdir(check): regutil.RegisterNamedPath("PCBuild",check) *************** *** 458,462 **** searchPath.append("..\\..\\lib") searchPath.append("..\\build") ! searchPath.append("..\\..\\pcbuild") print("Attempting to setup/repair the Python core") --- 463,470 ---- searchPath.append("..\\..\\lib") searchPath.append("..\\build") ! if "64 bit" in sys.version: ! searchPath.append("..\\..\\pcbuild\\amd64") ! else: ! searchPath.append("..\\..\\pcbuild") print("Attempting to setup/repair the Python core") |
From: Mark H. <mha...@us...> - 2009-01-27 06:27:18
|
Update of /cvsroot/pywin32/pywin32/win32/src In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv24522/win32/src Modified Files: win32rasmodule.cpp Log Message: Use more recent WINVER to enable user identity functionality Index: win32rasmodule.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/win32rasmodule.cpp,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** win32rasmodule.cpp 11 Dec 2008 00:25:40 -0000 1.15 --- win32rasmodule.cpp 27 Jan 2009 06:27:09 -0000 1.16 *************** *** 14,23 **** #ifndef WINVER // hrm - the RASEAPUSERIDENTITY structures on the Vista SDK now want ! // a WINVER > 0x500. ! # ifdef _WIN64 ! # define WINVER 0x501 ! # else ! # define WINVER 0x400 ! # endif #endif --- 14,18 ---- #ifndef WINVER // hrm - the RASEAPUSERIDENTITY structures on the Vista SDK now want ! #define WINVER 0x501 #endif *************** *** 91,97 **** if (pfnPyWinObject_AsRASEAPUSERIDENTITY == NULL) { #ifdef _DEBUG ! HMODULE hmod = GetModuleHandle("win2kras_d.pyd"); #else ! HMODULE hmod = GetModuleHandle("win2kras.pyd"); #endif if (hmod==NULL) { --- 86,92 ---- if (pfnPyWinObject_AsRASEAPUSERIDENTITY == NULL) { #ifdef _DEBUG ! HMODULE hmod = GetModuleHandle(_T("win2kras_d.pyd")); #else ! HMODULE hmod = GetModuleHandle(_T("win2kras.pyd")); #endif if (hmod==NULL) { |
From: Mark H. <mha...@us...> - 2009-01-27 06:26:05
|
Update of /cvsroot/pywin32/pywin32/Pythonwin/pywin/framework In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv24388/Pythonwin/pywin/framework Modified Files: mdi_pychecker.py Log Message: Fix locating PCBuild dir on 64bit builds Index: mdi_pychecker.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/Pythonwin/pywin/framework/mdi_pychecker.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** mdi_pychecker.py 14 Nov 2008 00:22:25 -0000 1.4 --- mdi_pychecker.py 27 Jan 2009 06:25:56 -0000 1.5 *************** *** 291,295 **** py = os.path.join(sys.prefix, 'python.exe') if not os.path.isfile(py): ! py = os.path.join(sys.prefix, 'PCBuild', 'python.exe') try: py = win32api.GetShortPathName(py) --- 291,298 ---- py = os.path.join(sys.prefix, 'python.exe') if not os.path.isfile(py): ! if "64 bit" in sys.version: ! py = os.path.join(sys.prefix, 'PCBuild', 'amd64', 'python.exe') ! else: ! py = os.path.join(sys.prefix, 'PCBuild', 'python.exe') try: py = win32api.GetShortPathName(py) |
From: Mark H. <mha...@us...> - 2009-01-27 06:26:03
|
Update of /cvsroot/pywin32/pywin32/win32/scripts In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv24388/win32/scripts Modified Files: regsetup.py Log Message: Fix locating PCBuild dir on 64bit builds Index: regsetup.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/scripts/regsetup.py,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** regsetup.py 4 Dec 2008 03:38:20 -0000 1.18 --- regsetup.py 27 Jan 2009 06:25:57 -0000 1.19 *************** *** 113,117 **** found = os.path.join(sys.prefix, possibleRealNames) if not FileExists(found): # for developers ! found = os.path.join(sys.prefix, "PCBuild", possibleRealNames) if not FileExists(found): found = LocateFileName(possibleRealNames, searchPaths) --- 113,120 ---- found = os.path.join(sys.prefix, possibleRealNames) if not FileExists(found): # for developers ! if "64 bit" in sys.version: ! found = os.path.join(sys.prefix, "PCBuild", "amd64", possibleRealNames) ! else: ! found = os.path.join(sys.prefix, "PCBuild", possibleRealNames) if not FileExists(found): found = LocateFileName(possibleRealNames, searchPaths) *************** *** 342,345 **** --- 345,350 ---- # value check = os.path.join(sys.prefix, "PCBuild") + if "64 bit" in sys.version: + check = os.path.join(check, "amd64") if os.path.isdir(check): regutil.RegisterNamedPath("PCBuild",check) *************** *** 458,462 **** searchPath.append("..\\..\\lib") searchPath.append("..\\build") ! searchPath.append("..\\..\\pcbuild") print "Attempting to setup/repair the Python core" --- 463,470 ---- searchPath.append("..\\..\\lib") searchPath.append("..\\build") ! if "64 bit" in sys.version: ! searchPath.append("..\\..\\pcbuild\\amd64") ! else: ! searchPath.append("..\\..\\pcbuild") print "Attempting to setup/repair the Python core" |
From: Mark H. <mha...@us...> - 2009-01-27 06:26:02
|
Update of /cvsroot/pywin32/pywin32/com/win32com/server In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv24388/com/win32com/server Modified Files: register.py Log Message: Fix locating PCBuild dir on 64bit builds Index: register.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/server/register.py,v retrieving revision 1.25 retrieving revision 1.26 diff -C2 -d -r1.25 -r1.26 *** register.py 28 Dec 2008 10:10:50 -0000 1.25 --- register.py 27 Jan 2009 06:25:56 -0000 1.26 *************** *** 100,104 **** if not os.path.exists(exeName): # See if in our sys.prefix/pcbuild directory (for developers) ! exeName = os.path.join( sys.prefix, "PCbuild", exeBaseName ) if not os.path.exists(exeName): # See if the registry has some info. --- 100,107 ---- if not os.path.exists(exeName): # See if in our sys.prefix/pcbuild directory (for developers) ! if "64 bit" in sys.version: ! exeName = os.path.join( sys.prefix, "PCbuild", "amd64", exeBaseName ) ! else: ! exeName = os.path.join( sys.prefix, "PCbuild", exeBaseName ) if not os.path.exists(exeName): # See if the registry has some info. |
From: Mark H. <mha...@us...> - 2009-01-27 06:25:12
|
Update of /cvsroot/pywin32/pywin32 In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv24316 Modified Files: pywin32_postinstall.py Log Message: use exception attributes Index: pywin32_postinstall.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/pywin32_postinstall.py,v retrieving revision 1.30 retrieving revision 1.31 diff -C2 -d -r1.30 -r1.31 *** pywin32_postinstall.py 5 Dec 2008 23:59:14 -0000 1.30 --- pywin32_postinstall.py 27 Jan 2009 06:25:02 -0000 1.31 *************** *** 368,372 **** RegisterCOMObjects() except win32api.error, details: ! if details[0]!=5: # ERROR_ACCESS_DENIED raise print "You do not have the permissions to install COM objects." --- 368,372 ---- RegisterCOMObjects() except win32api.error, details: ! if details.winerror!=5: # ERROR_ACCESS_DENIED raise print "You do not have the permissions to install COM objects." |
From: Mark H. <mha...@us...> - 2009-01-26 01:23:45
|
Update of /cvsroot/pywin32/pywin32/win32/src In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv12129/win32/src Modified Files: PyTime.cpp Log Message: ensure Format() always returns a unicode object on py3k Index: PyTime.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/PyTime.cpp,v retrieving revision 1.25 retrieving revision 1.26 diff -C2 -d -r1.25 -r1.26 *** PyTime.cpp 26 Jan 2009 00:47:31 -0000 1.25 --- PyTime.cpp 26 Jan 2009 01:23:38 -0000 1.26 *************** *** 202,206 **** if (!_tcsftime(szBuffer, 256/*_countof()*/, fmt, &tm)) szBuffer[0] = '\0'; // Better error? ! PyObject *rc = PyWinObject_FromTCHAR(szBuffer); if (bFreeString) PyWinObject_FreeTCHAR(fmt); return rc; --- 202,206 ---- if (!_tcsftime(szBuffer, 256/*_countof()*/, fmt, &tm)) szBuffer[0] = '\0'; // Better error? ! PyObject *rc = PyWinCoreString_FromString(szBuffer); if (bFreeString) PyWinObject_FreeTCHAR(fmt); return rc; |