desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Move to the next bookmark'
def GotoNextBookmarkEvent(self, event, fromPos=(-1)):
if (fromPos == (-1)): (fromPos, end) = self.GetSel() startLine = (self.LineFromChar(fromPos) + 1) nextLine = (self.GetDocument().MarkerGetNext((startLine + 1), MARKER_BOOKMARK) - 1) if (nextLine < 0): nextLine = (self.GetDocument().MarkerGetNext(0, MARKER_BOOKMARK) - 1) if ((nextLine < 0) or (nextLine == (startLine - 1))): win32api.MessageBeep() else: self.SCIEnsureVisible(nextLine) self.SCIGotoLine(nextLine) return 0
'Insert an indent. If no selection, a single indent, otherwise a block indent'
def TabKeyEvent(self, event):
if self.SCIAutoCActive(): self.SCIAutoCComplete() return 0 return self.bindings.fire('<<smart-indent>>', event)
'Handle the enter key with special handling for auto-complete'
def EnterKeyEvent(self, event):
if self.SCIAutoCActive(): self.SCIAutoCComplete() self.SCIAutoCCancel() return self.bindings.fire('<<newline-and-indent>>', event)
'Returns a list of property pages'
def GetPythonPropertyPages(self):
from pywin.scintilla import configui return (EditorTemplateBase.GetPythonPropertyPages(self) + [configui.ScintillaFormatPropertyPage()])
'Take a command and stick it at the end of the buffer (with python prompts inserted if required).'
def AppendToPrompt(self, bufLines, oldPrompt=None):
self.flush() lastLineNo = (self.GetLineCount() - 1) line = self.DoGetLine(lastLineNo) if (oldPrompt and (line == oldPrompt)): self.SetSel((self.GetTextLength() - len(oldPrompt)), self.GetTextLength()) self.ReplaceSel(sys.ps1) elif (line != str(sys.ps1)): if (len(line) != 0): self.write('\n') self.write(sys.ps1) self.flush() self.idle.text.mark_set('iomark', 'end-1c') if (not bufLines): return terms = (([('\n' + sys.ps2)] * (len(bufLines) - 1)) + ['']) for (bufLine, term) in zip(bufLines, terms): if bufLine.strip(): self.write((bufLine + term)) self.flush()
'Sanitizes code from interactive window, removing prompts and output, and inserts it in the clipboard.'
def OnEditCopyCode(self, command, code):
code = self.GetSelText() lines = code.splitlines() out_lines = [] for line in lines: if line.startswith(sys.ps1): line = line[len(sys.ps1):] out_lines.append(line) elif line.startswith(sys.ps2): line = line[len(sys.ps2):] out_lines.append(line) out_code = os.linesep.join(out_lines) win32clipboard.OpenClipboard() try: win32clipboard.SetClipboardData(win32clipboard.CF_UNICODETEXT, unicode(out_code)) finally: win32clipboard.CloseClipboard()
'Executes python code directly from the clipboard.'
def OnEditExecClipboard(self, command, code):
win32clipboard.OpenClipboard() try: code = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT) finally: win32clipboard.CloseClipboard() code = (code.replace('\r\n', '\n') + '\n') try: o = compile(code, '<clipboard>', 'exec') exec o in __main__.__dict__ except: traceback.print_exc()
'Forward most functions to the real sys.stdin for absolute realism.'
def __getattr__(self, name):
if (self.real_file is None): raise AttributeError(name) return getattr(self.real_file, name)
'Return 1 if the file is connected to a tty(-like) device, else 0.'
def isatty(self):
return 1
'Read at most size bytes from the file (less if the read hits EOF or no more data is immediately available on a pipe, tty or similar device). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. (For certain files, like ttys, it makes sense to continue reading after an EOF is hit.)'
def read(self, size=(-1)):
result_size = self.__get_lines(size) return self.__extract_from_buffer(result_size)
'Read one entire line from the file. A trailing newline character is kept in the string2.6 (but may be absent when a file ends with an incomplete line). If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. An empty string is returned when EOF is hit immediately. Note: unlike stdio\'s fgets(), the returned string contains null characters (\'\') if they occurred in the input.'
def readline(self, size=(-1)):
maximum_result_size = self.__get_lines(size, (lambda buffer: ('\n' in buffer))) if ('\n' in self.buffer[:maximum_result_size]): result_size = (self.buffer.find('\n', 0, maximum_result_size) + 1) assert (result_size > 0) else: result_size = maximum_result_size return self.__extract_from_buffer(result_size)
'Remove the first character_count characters from the internal buffer and return them.'
def __extract_from_buffer(self, character_count):
result = self.buffer[:character_count] self.buffer = self.buffer[character_count:] return result
'Keep adding lines to our internal buffer until done_reading(self.buffer) is true or EOF has been reached or we have desired_size bytes in the buffer. If desired_size < 0, we are never satisfied until we reach EOF. If done_reading is not supplied, it is not consulted. If desired_size < 0, returns the length of the internal buffer. Otherwise, returns desired_size.'
def __get_lines(self, desired_size, done_reading=(lambda buffer: False)):
while ((not done_reading(self.buffer)) and ((desired_size < 0) or (len(self.buffer) < desired_size))): try: self.__get_line() except (EOFError, KeyboardInterrupt): desired_size = len(self.buffer) if (desired_size < 0): return len(self.buffer) else: return desired_size
'Grab one line from get_input_line() and append it to the buffer.'
def __get_line(self):
line = get_input_line() print '>>>', line self.buffer = ((self.buffer + line) + '\n')
'Read until EOF using readline() and return a list containing the lines thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read.'
def readlines(self, *sizehint):
result = [] total_read = 0 while ((sizehint == ()) or (total_read < sizehint[0])): line = self.readline() if (line == ''): break total_read = (total_read + len(line)) result.append(line) return result
'Called to crank up the app'
def InitInstance(self):
numMRU = win32ui.GetProfileVal('Settings', 'Recent File List Size', 10) win32ui.LoadStdProfileSettings(numMRU) if (win32api.GetVersionEx()[0] < 4): win32ui.SetDialogBkColor() win32ui.Enable3dControls() self.LoadMainFrame() self.SetApplicationPaths()
'Called as the app dies - too late to prevent it here!'
def ExitInstance(self):
win32ui.OutputDebug('Application shutdown\n') try: win32ui.InstallCallbackCaller(self.oldCallbackCaller) except AttributeError: pass if self.oldCallbackCaller: del self.oldCallbackCaller self.frame = None self.idleHandlers = [] if self._obj_: self._obj_.AttachObject(None) self._obj_ = None global App global AppBuilder App = None AppBuilder = None return 0
'Create the main applications frame'
def LoadMainFrame(self):
self.frame = self.CreateMainFrame() self.SetMainFrame(self.frame) self.frame.LoadFrame(win32ui.IDR_MAINFRAME, win32con.WS_OVERLAPPEDWINDOW) self.frame.DragAcceptFiles() self.frame.ShowWindow(win32ui.GetInitialStateRequest()) self.frame.UpdateWindow() self.HookCommands()
'Handle right click message'
def OnRClick(self, params):
menu = win32ui.LoadMenu(win32ui.IDR_TEXTTYPE).GetSubMenu(0) menu.TrackPopupMenu(params[5]) return 0
'Handle a file being dropped from file manager'
def OnDropFiles(self, msg):
hDropInfo = msg[2] self.frame.SetActiveWindow() nFiles = win32api.DragQueryFile(hDropInfo) try: for iFile in range(0, nFiles): fileName = win32api.DragQueryFile(hDropInfo, iFile) win32ui.GetApp().OpenDocumentFile(fileName) finally: win32api.DragFinish(hDropInfo) return 0
'Called when a File 1-n message is recieved'
def OnFileMRU(self, id, code):
fileName = win32ui.GetRecentFileList()[(id - win32ui.ID_FILE_MRU_FILE1)] win32ui.GetApp().OpenDocumentFile(fileName)
'Called when FileOpen message is received'
def HandleOnFileOpen(self, id, code):
win32ui.GetApp().OnFileOpen()
'Called when FileNew message is received'
def HandleOnFileNew(self, id, code):
win32ui.GetApp().OnFileNew()
'Called when HelpAbout message is received. Displays the About dialog.'
def OnHelpAbout(self, id, code):
win32ui.InitRichEdit() dlg = AboutBox() dlg.DoModal()
'init the output window - Params title=None -- What is the title of the window defSize=None -- What is the default size for the window - if this is a string, the size will be loaded from the ini file. queueing = flags.WQ_LINE -- When should output be written bAutoRestore=1 -- Should a minimized window be restored. style -- Style for Window, or None for default. makeDoc, makeFrame, makeView -- Classes for frame, view and window respectively.'
def __init__(self, title=None, defSize=None, queueing=flags.WQ_LINE, bAutoRestore=1, style=None, makeDoc=None, makeFrame=None, makeView=None):
if (makeDoc is None): makeDoc = WindowOutputDocument if (makeFrame is None): makeFrame = WindowOutputFrame if (makeView is None): makeView = WindowOutputViewScintilla docview.DocTemplate.__init__(self, win32ui.IDR_PYTHONTYPE, makeDoc, makeFrame, makeView) self.SetDocStrings('\nOutput\n\n\n\n\n\n') win32ui.GetApp().AddDocTemplate(self) self.writeQueueing = queueing self.errorCantRecreate = 0 self.killBuffer = [] self.style = style self.bAutoRestore = bAutoRestore self.title = title self.bCreating = 0 self.interruptCount = 0 if (type(defSize) == type('')): self.iniSizeSection = defSize self.defSize = app.LoadWindowSize(defSize) self.loadedSize = self.defSize else: self.iniSizeSection = None self.defSize = defSize self.currentView = None self.outputQueue = Queue.Queue((-1)) self.mainThreadId = win32api.GetCurrentThreadId() self.idleHandlerSet = 0 self.SetIdleHandler()
'Called when ViewBrowse message is received'
def OnViewBrowse(self, id, code):
from pywin.mfc import dialog from pywin.tools import browser obName = dialog.GetSimpleInput('Object', '__builtins__', 'Browse Python Object') if (obName is None): return try: browser.Browse(eval(obName, __main__.__dict__, __main__.__dict__)) except NameError: win32ui.MessageBox('This is no object with this name') except AttributeError: win32ui.MessageBox('The object has no attribute of that name') except: traceback.print_exc() win32ui.MessageBox('This object can not be browsed')
'Called when a FileImport message is received. Import the current or specified file'
def OnFileImport(self, id, code):
import scriptutils scriptutils.ImportFile()
'Called when a FileCheck message is received. Check the current file.'
def OnFileCheck(self, id, code):
import scriptutils scriptutils.CheckFile()
'Called when a FileRun message is received.'
def OnFileRun(self, id, code):
import scriptutils showDlg = (win32api.GetKeyState(win32con.VK_SHIFT) >= 0) scriptutils.RunScript(None, None, showDlg)
'Return the template used to create this dialog'
def GetTemplate(self):
w = 152 h = 122 SS_STD = (win32con.WS_CHILD | win32con.WS_VISIBLE) FRAMEDLG_STD = (win32con.WS_CAPTION | win32con.WS_SYSMENU) style = (((FRAMEDLG_STD | win32con.WS_VISIBLE) | win32con.DS_SETFONT) | win32con.WS_MINIMIZEBOX) template = [[self.caption, (0, 0, w, h), style, None, (8, 'Helv')]] lvStyle = ((((((SS_STD | commctrl.LVS_EDITLABELS) | commctrl.LVS_REPORT) | commctrl.LVS_AUTOARRANGE) | commctrl.LVS_ALIGNLEFT) | win32con.WS_BORDER) | win32con.WS_TABSTOP) template.append(['SysListView32', '', self.IDC_LISTVIEW, (10, 10, 185, 100), lvStyle]) return template
'LPARAM for EM_FINDTEXTEX: typedef struct _findtextex { CHARRANGE chrg; LPCTSTR lpstrText; CHARRANGE chrgText;} FINDTEXTEX; typedef struct _charrange { LONG cpMin; LONG cpMax;} CHARRANGE;'
def FindText(self, flags, range, findText):
findtextex_fmt = 'llPll' txt_buff = (findText + '\x00').encode(default_scintilla_encoding) txt_array = array.array('b', txt_buff) ft_buff = struct.pack(findtextex_fmt, range[0], range[1], txt_array.buffer_info()[0], 0, 0) ft_array = array.array('b', ft_buff) rc = self.SendScintilla(EM_FINDTEXTEX, flags, ft_array.buffer_info()[0]) ftUnpacked = struct.unpack(findtextex_fmt, ft_array) return (rc, (ftUnpacked[3], ftUnpacked[4]))
'Binds an event to a Windows control/command ID'
def bind_command(self, event, id=0):
id = assign_command_id(event, id) return id
'typedef struct _formatrange { HDC hdc; HDC hdcTarget; RECT rc; RECT rcPage; CHARRANGE chrg;} FORMATRANGE;'
def FormatRange(self, dc, pageStart, lengthDoc, rc, draw):
fmt = 'PPIIIIIIIIll' hdcRender = dc.GetHandleOutput() hdcFormat = dc.GetHandleAttrib() fr = struct.pack(fmt, hdcRender, hdcFormat, rc[0], rc[1], rc[2], rc[3], rc[0], rc[1], rc[2], rc[3], pageStart, lengthDoc) nextPageStart = self.SendScintilla(EM_FORMATRANGE, draw, fr) return nextPageStart
'id is the resource ID, or a template dllid may be None, a dll object, or a string with a dll name'
def __init__(self, id, dllid=None):
self.dll = dllFromDll(dllid) if (type(id) == type([])): dlg = win32ui.CreateDialogIndirect(id) else: dlg = win32ui.CreateDialog(id, self.dll) window.Wnd.__init__(self, dlg) self.HookCommands() self.bHaveInit = None
'DoModal has finished. Can now access the users choices'
def OnOK(self):
self._obj_.OnOK() pInfo = self.pInfo flags = pInfo.GetFlags() self['toFile'] = ((flags & win32ui.PD_PRINTTOFILE) != 0) self['direct'] = pInfo.GetDirect() self['preview'] = pInfo.GetPreview() self['continuePrinting'] = pInfo.GetContinuePrinting() self['curPage'] = pInfo.GetCurPage() self['numPreviewPages'] = pInfo.GetNumPreviewPages() self['userData'] = pInfo.GetUserData() self['draw'] = pInfo.GetDraw() self['pageDesc'] = pInfo.GetPageDesc() self['minPage'] = pInfo.GetMinPage() self['maxPage'] = pInfo.GetMaxPage() self['offsetPage'] = pInfo.GetOffsetPage() self['fromPage'] = pInfo.GetFromPage() self['toPage'] = pInfo.GetToPage() self['copies'] = pInfo.GetCopies() self['deviceName'] = pInfo.GetDeviceName() self['driverName'] = pInfo.GetDriverName() self['printAll'] = pInfo.PrintAll() self['printCollate'] = pInfo.PrintCollate() self['printRange'] = pInfo.PrintRange() self['printSelection'] = pInfo.PrintSelection() del self.pInfo
'id is the resource ID dllid may be None, a dll object, or a string with a dll name'
def __init__(self, id, dllid=None, caption=0):
self.dll = dllFromDll(dllid) if self.dll: oldRes = win32ui.SetResource(self.dll) if (type(id) == type([])): dlg = win32ui.CreatePropertyPageIndirect(id) else: dlg = win32ui.CreatePropertyPage(id, caption) if self.dll: win32ui.SetResource(oldRes) window.Wnd.__init__(self, dlg) self.HookCommands()
'Initialize a property sheet. pageList is a list of ID\'s'
def __init__(self, caption, dll=None, pageList=None):
self.dll = dllFromDll(dll) self.sheet = win32ui.CreatePropertySheet(caption) window.Wnd.__init__(self, self.sheet) if (not (pageList is None)): self.AddPage(pageList)
'Page may be page, or int ID. Assumes DLL setup'
def DoAddSinglePage(self, page):
if (type(page) == type(0)): self.sheet.AddPage(win32ui.CreatePropertyPage(page)) else: self.sheet.AddPage(page)
'Constructor -- initialize the table of writers'
def __init__(self):
self.writers = {} self.origStdOut = None
'Register the writer for the current thread'
def register(self, writer):
self.writers[thread.get_ident()] = writer if (self.origStdOut is None): self.origStdOut = sys.stdout sys.stdout = self
'Remove the writer for the current thread, if any'
def unregister(self):
try: del self.writers[thread.get_ident()] except KeyError: pass if (len(self.writers) == 0): sys.stdout = self.origStdOut self.origStdOut = None
'Return the current thread\'s writer, default sys.stdout'
def getwriter(self):
try: return self.writers[thread.get_ident()] except KeyError: return self.origStdOut
'Write to the current thread\'s writer, default sys.stdout'
def write(self, str):
self.getwriter().write(str)
'Create the main applications frame'
def LoadMainFrame(self):
self.frame = self.CreateMainFrame() self.SetMainFrame(self.frame) self.frame.LoadFrame(win32ui.IDR_DEBUGGER, win32con.WS_OVERLAPPEDWINDOW) self.frame.DragAcceptFiles() self.frame.ShowWindow(win32con.SW_HIDE) self.frame.UpdateWindow() self.HookCommands()
'Public interface into debugger options'
def get_option(self, option):
try: return self.options[option] except KeyError: raise error(('Option %s is not a valid option' % option))
'Called as the GUI debugger is about to get context, and take control of the running program.'
def GUIAboutToBreak(self):
self.GUICheckInit() self.RespondDebuggerState(DBGSTATE_BREAK) self.GUIAboutToInteract() if self.pumping: print '!!! Already pumping - outa here' return self.pumping = 1 win32ui.StartDebuggerPump() assert (not self.pumping), 'Should not be pumping once the pump has finished' if self.frameShutdown: win32ui.GetMainFrame().PostMessage(win32con.WM_CLOSE)
'Called as the GUI is about to perform any interaction with the user'
def GUIAboutToInteract(self):
frame = win32ui.GetMainFrame() self.bFrameEnabled = frame.IsWindowEnabled() self.oldForeground = None fw = win32ui.GetForegroundWindow() if (fw is not frame): self.oldForeground = fw self.oldFrameEnableState = frame.IsWindowEnabled() frame.EnableWindow(1) if (self.inForcedGUI and (not frame.IsWindowVisible())): frame.ShowWindow(win32con.SW_SHOW) frame.UpdateWindow() if self.curframe: SetInteractiveContext(self.curframe.f_globals, self.curframe.f_locals) else: SetInteractiveContext(None, None) self.GUIRespondDebuggerData()
'Called as the GUI is about to finish any interaction with the user Returns non zero if we are allowed to stop interacting'
def GUIAboutToFinishInteract(self):
if (self.oldForeground is not None): try: win32ui.GetMainFrame().EnableWindow(self.oldFrameEnableState) self.oldForeground.EnableWindow(1) except win32ui.error: pass if (not self.inForcedGUI): return 1 for template in win32ui.GetApp().GetDocTemplateList(): for doc in template.GetDocumentList(): if (not doc.SaveModified()): return 0 if self.get_option(OPT_HIDE): frame = win32ui.GetMainFrame() frame.ShowWindow(win32con.SW_HIDE) return 1
'Unshow the current line, and forget it'
def _UnshowCurrentLine(self):
if (self.shownLineCurrent is not None): (fname, lineno) = self.shownLineCurrent self.ResetLineState(fname, lineno, LINESTATE_CURRENT) self.shownLineCurrent = None
'RCParser.loadDialogs(rcFileName) -> None Load the dialog information into the parser. Dialog Definations can then be accessed using the "dialogs" dictionary member (name->DialogDef). The "ids" member contains the dictionary of id->name. The "names" member contains the dictionary of name->id'
def load(self, rcstream):
self.open(rcstream) self.getToken() while (self.token != None): self.parse() self.getToken()
'Try to construct a TimeZoneDefinition from a) [DYNAMIC_]TIME_ZONE_INFORMATION args b) another TimeZoneDefinition c) a byte structure (using _from_bytes)'
def __init__(self, *args, **kwargs):
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__))
'Windows Platform SDK GetTimeZoneInformation'
@classmethod def current(class_):
(code, tzi) = win32api.GetTimeZoneInformation(True) return (code, class_(*tzi))
'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'
@staticmethod def _locate_day(year, cutoff):
target_weekday = ((cutoff.day_of_week + 6) % 7) week_of_month = cutoff.day day = (((week_of_month - 1) * 7) + 1) result = datetime.datetime(year, cutoff.month, day, cutoff.hour, cutoff.minute, cutoff.second, cutoff.millisecond) days_to_go = ((target_weekday - result.weekday()) % 7) result += datetime.timedelta(days_to_go) while (result.month == (cutoff.month + 1)): result -= datetime.timedelta(weeks=1) return result
'Find the registry key for the time zone name (self.timeZoneName).'
def _FindTimeZoneKey(self):
zoneNames = dict(self._get_indexed_time_zone_keys('Std')) 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
'Loads the information from an opened time zone registry key into relevant fields of this TZI object'
def _LoadInfoFromKey(self):
key = self._FindTimeZoneKey() self.displayName = key['Display'] self.standardName = key['Std'] self.daylightName = key['Dlt'] self.staticInfo = TimeZoneDefinition(key['TZI']) self._LoadDynamicInfoFromKey(key)
'Calculates the utcoffset according to the datetime.tzinfo spec'
def utcoffset(self, dt):
if (dt is None): return winInfo = self.getWinInfo(dt.year) return (- (winInfo.bias + self.dst(dt)))
'Calculates the daylight savings offset according to the datetime.tzinfo spec'
def dst(self, dt):
if (dt is None): return winInfo = self.getWinInfo(dt.year) if ((not self.fixedStandardTime) and self._inDaylightSavings(dt)): result = winInfo.daylight_bias else: result = winInfo.standard_bias return result
'Given a year, determines the time when daylight savings time starts'
def GetDSTStartTime(self, year):
return self.getWinInfo(year).locate_daylight_start(year)
'Given a year, determines the time when daylight savings ends.'
def GetDSTEndTime(self, year):
return self.getWinInfo(year).locate_standard_start(year)
'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'
@classmethod def local(class_):
(code, info) = TimeZoneDefinition.current() fix_standard_time = (not code) return class_(info, fix_standard_time)
'Returns a time-zone representing UTC. Same as TimeZoneInfo(\'GMT Standard Time\', True) but caches the result for performance. >>> isinstance(TimeZoneInfo.utc(), TimeZoneInfo) True'
@classmethod def utc(class_):
if (not ('_tzutc' in class_.__dict__)): setattr(class_, '_tzutc', class_('GMT Standard Time', True)) return class_._tzutc
'Return the registry key that stores time zone details'
@staticmethod def _get_time_zone_key(subkey=None):
key = _RegKeyDict.open(_winreg.HKEY_LOCAL_MACHINE, TimeZoneInfo.tzRegKey) if subkey: key = key.subkey(subkey) return key
'Returns the names of the (registry keys of the) time zones'
@staticmethod def _get_time_zone_key_names():
return TimeZoneInfo._get_time_zone_key().subkeys()
'Get the names of the registry keys indexed by a value in that key.'
@staticmethod def _get_indexed_time_zone_keys(index_key='Index'):
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)
'Return a list of time zone names that can be used to initialize TimeZoneInfo instances'
@staticmethod def get_sorted_time_zone_names():
tzs = TimeZoneInfo.get_sorted_time_zones() get_standard_name = (lambda tzi: tzi.standardName) return [get_standard_name(tz) for tz in tzs]
'Return the time zones sorted by some key. key must be a function that takes a TimeZoneInfo object and returns a value suitable for sorting on. The key defaults to the bias (descending), as is done in Windows (see http://blogs.msdn.com/michkap/archive/2006/12/22/1350684.aspx)'
@staticmethod def get_sorted_time_zones(key=None):
key = (key or (lambda tzi: (- tzi.staticInfo.bias))) zones = TimeZoneInfo.get_all_time_zones() zones.sort(key=key) return zones
'Enumerates an open registry key as an iterable generator'
@staticmethod def _enumerate_reg(key, func):
try: for index in count(): (yield func(key, index)) except WindowsError: pass
'The PDH Query object is initialised with a single, optional list argument, that must be properly formatted PDH Counter paths. Generally this list will only be provided by the class when it is being unpickled (removed from storage). Normal use is to call the class with no arguments and use the various addcounter functions (particularly, for end user\'s, the use of addcounterbybrowsing is the most common approach) You might want to provide the list directly if you want to hard-code the elements with which your query deals (and thereby avoid the overhead of unpickling the class).'
def __init__(self, paths=None):
self.counters = [] if paths: self.paths = paths else: self.paths = [] self._base = None self.active = 0 self.curpaths = []
'Adds possibly multiple paths to the paths attribute of the query, does this by calling the standard counter browsing dialogue. Within this dialogue, find the counter you want to log, and click: Add, repeat for every path you want to log, then click on close. The paths are appended to the non-volatile paths list for this class, subclasses may create a function which parses the paths and decides (via heuristics) whether to add the path to the volatile or non-volatile path list. e.g.: query.addcounter()'
def addcounterbybrowsing(self, flags=win32pdh.PERF_DETAIL_WIZARD, windowtitle='Python Browser'):
win32pdh.BrowseCounters(None, 0, self.paths.append, flags, windowtitle)
'Adds a single counter path, without catching any exceptions. See addcounter for details.'
def rawaddcounter(self, object, counter, instance=None, inum=(-1), machine=None):
path = win32pdh.MakeCounterPath((machine, object, instance, None, inum, counter)) self.paths.append(path)
'Adds a single counter path to the paths attribute. Normally this will be called by a child class\' speciality functions, rather than being called directly by the user. (Though it isn\'t hard to call manually, since almost everything is given a default) This method is only functional when the query is closed (or hasn\'t yet been opened). This is to prevent conflict in multi-threaded query applications). e.g.: query.addcounter(\'Memory\',\'Available Bytes\')'
def addcounter(self, object, counter, instance=None, inum=(-1), machine=None):
if (not self.active): try: self.rawaddcounter(object, counter, instance, inum, machine) return 0 except win32api.error: return (-1) else: return (-1)
'Build the base query object for this wrapper, then add all of the counters required for the query. Raise a QueryError if we can\'t complete the functions. If we are already open, then do nothing.'
def open(self):
if (not self.active): self.curpaths = copy.copy(self.paths) try: base = win32pdh.OpenQuery() for path in self.paths: try: self.counters.append(win32pdh.AddCounter(base, path)) except win32api.error: self.counters.append(0) pass self._base = base self.active = 1 return 0 except: try: self.killbase(base) except NameError: pass self.active = 0 self.curpaths = [] raise QueryError(self) return 1
'### This is not a public method Mission critical function to kill the win32pdh objects held by this object. User\'s should generally use the close method instead of this method, in case a sub-class has overridden close to provide some special functionality.'
def killbase(self, base=None):
self._base = None counters = self.counters self.counters = [] self.active = 0 try: map(win32pdh.RemoveCounter, counters) except: pass try: win32pdh.CloseQuery(base) except: pass del counters del base
'Makes certain that the underlying query object has been closed, and that all counters have been removed from it. This is important for reference counting. You should only need to call close if you have previously called open. The collectdata methods all can handle opening and closing the query. Calling close multiple times is acceptable.'
def close(self):
try: self.killbase(self._base) except AttributeError: self.killbase()
'Returns the formatted current values for the Query'
def collectdata(self, format=win32pdh.PDH_FMT_LONG):
if self._base: return self.collectdataslave(format) else: self.open() temp = self.collectdataslave(format) self.close() return temp
'### Not a public method Called only when the Query is known to be open, runs over the whole set of counters, appending results to the temp, returns the values as a list.'
def collectdataslave(self, format=win32pdh.PDH_FMT_LONG):
try: win32pdh.CollectQueryData(self._base) temp = [] for counter in self.counters: ok = 0 try: if counter: temp.append(win32pdh.GetFormattedCounterValue(counter, format)[1]) ok = 1 except win32api.error: pass if (not ok): temp.append((-1)) return temp except win32api.error: return ([(-1)] * len(self.counters))
'### Not a public method'
def __getinitargs__(self):
return (self.paths,)
'The PDH Query object is initialised with a single, optional list argument, that must be properly formatted PDH Counter paths. Generally this list will only be provided by the class when it is being unpickled (removed from storage). Normal use is to call the class with no arguments and use the various addcounter functions (particularly, for end user\'s, the use of addcounterbybrowsing is the most common approach) You might want to provide the list directly if you want to hard-code the elements with which your query deals (and thereby avoid the overhead of unpickling the class).'
def __init__(self, *args, **namedargs):
self.volatilecounters = [] BaseQuery.__init__(*((self,) + args), **namedargs)
'A "Performance Counter" is a stable, known, common counter, such as Memory, or Processor. The use of addperfcounter by end-users is deprecated, since the use of addcounterbybrowsing is considerably more flexible and general. It is provided here to allow the easy development of scripts which need to access variables so common we know them by name (such as Memory|Available Bytes), and to provide symmetry with the add inst counter method. usage: query.addperfcounter(\'Memory\', \'Available Bytes\') It is just as easy to access addcounter directly, the following has an identicle effect. query.addcounter(\'Memory\', \'Available Bytes\')'
def addperfcounter(self, object, counter, machine=None):
BaseQuery.addcounter(self, object=object, counter=counter, machine=machine)
'The purpose of using an instcounter is to track particular instances of a counter object (e.g. a single processor, a single running copy of a process). For instance, to track all python.exe instances, you would need merely to ask: query.addinstcounter(\'python\',\'Virtual Bytes\') You can find the names of the objects and their available counters by doing an addcounterbybrowsing() call on a query object (or by looking in performance monitor\'s add dialog.) Beyond merely rearranging the call arguments to make more sense, if the volatile flag is true, the instcounters also recalculate the paths of the available instances on every call to open the query.'
def addinstcounter(self, object, counter, machine=None, objtype='Process', volatile=1, format=win32pdh.PDH_FMT_LONG):
if volatile: self.volatilecounters.append((object, counter, machine, objtype, format)) else: self.paths[len(self.paths):] = self.getinstpaths(object, counter, machine, objtype, format)
'### Not an end-user function Calculate the paths for an instance object. Should alter to allow processing for lists of object-counter pairs.'
def getinstpaths(self, object, counter, machine=None, objtype='Process', format=win32pdh.PDH_FMT_LONG):
(items, instances) = win32pdh.EnumObjectItems(None, None, objtype, (-1)) instances.sort() try: cur = instances.index(object) except ValueError: return [] temp = [object] try: while (instances[(cur + 1)] == object): temp.append(object) cur = (cur + 1) except IndexError: pass paths = [] for ind in range(len(temp)): paths.append(win32pdh.MakeCounterPath((machine, 'Process', object, None, ind, counter))) return paths
'Explicitly open a query: When you are needing to make multiple calls to the same query, it is most efficient to open the query, run all of the calls, then close the query, instead of having the collectdata method automatically open and close the query each time it runs. There are currently no arguments to open.'
def open(self, *args, **namedargs):
BaseQuery.open(*((self,) + args), **namedargs) paths = [] for tup in self.volatilecounters: paths[len(paths):] = self.getinstpaths(*tup) for path in paths: try: self.counters.append(win32pdh.AddCounter(self._base, path)) self.curpaths.append(path) except win32api.error: pass
'Non-threaded collection of performance data: This method allows you to specify the total period for which you would like to run the Query, and the time interval between individual runs. The collected data is stored in query.curresults at the _end_ of the run. The pathnames for the query are stored in query.curpaths. e.g.: query.collectdatafor(30,2) Will collect data for 30seconds at 2 second intervals'
def collectdatafor(self, totalperiod, period=1):
tempresults = [] try: self.open() for ind in xrange((totalperiod / period)): tempresults.append(self.collectdata()) time.sleep(period) self.curresults = tempresults finally: self.close()
'Threaded collection of performance data: This method sets up a simple semaphor system for signalling when you would like to start and stop a threaded data collection method. The collection runs every period seconds until the semaphor attribute is set to a non-true value (which normally should be done by calling query.collectdatawhile_stop() .) e.g.: query.collectdatawhile(2) # starts the query running, returns control to the caller immediately # is collecting data every two seconds. # do whatever you want to do while the thread runs, then call: query.collectdatawhile_stop() # when you want to deal with the data. It is generally a good idea # to sleep for period seconds yourself, since the query will not copy # the required data until the next iteration: time.sleep(2) # now you can access the data from the attributes of the query query.curresults query.curpaths'
def collectdatawhile(self, period=1):
self.collectdatawhile_active = 1 thread.start_new_thread(self.collectdatawhile_slave, (period,))
'Signals the collectdatawhile slave thread to stop collecting data on the next logging iteration.'
def collectdatawhile_stop(self):
self.collectdatawhile_active = 0
'### Not a public function Does the threaded work of collecting the data and storing it in an attribute of the class.'
def collectdatawhile_slave(self, period):
tempresults = [] try: self.open() while self.collectdatawhile_active: tempresults.append(self.collectdata()) time.sleep(period) self.curresults = tempresults finally: self.close()
'Reset everything to an unauthorized state'
def reset(self):
self.ctxt = None self.authenticated = False self.next_seq_num = 0
'Get the next sequence number for a transmission. Default implementation is to increment a counter'
def _get_next_seq_num(self):
ret = self.next_seq_num self.next_seq_num = (self.next_seq_num + 1) return ret
'Encrypt a string, returning a tuple of (encrypted_data, encryption_data). These can be passed to decrypt to get back the original string.'
def encrypt(self, data):
pkg_size_info = self.ctxt.QueryContextAttributes(sspicon.SECPKG_ATTR_SIZES) trailersize = pkg_size_info['SecurityTrailer'] encbuf = win32security.PySecBufferDescType() encbuf.append(win32security.PySecBufferType(len(data), sspicon.SECBUFFER_DATA)) encbuf.append(win32security.PySecBufferType(trailersize, sspicon.SECBUFFER_TOKEN)) encbuf[0].Buffer = data self.ctxt.EncryptMessage(0, encbuf, self._get_next_seq_num()) return (encbuf[0].Buffer, encbuf[1].Buffer)
'Decrypt a previously encrypted string, returning the orignal data'
def decrypt(self, data, trailer):
encbuf = win32security.PySecBufferDescType() encbuf.append(win32security.PySecBufferType(len(data), sspicon.SECBUFFER_DATA)) encbuf.append(win32security.PySecBufferType(len(trailer), sspicon.SECBUFFER_TOKEN)) encbuf[0].Buffer = data encbuf[1].Buffer = trailer self.ctxt.DecryptMessage(encbuf, self._get_next_seq_num()) return encbuf[0].Buffer
'sign a string suitable for transmission, returning the signature. Passing the data and signature to verify will determine if the data is unchanged.'
def sign(self, data):
pkg_size_info = self.ctxt.QueryContextAttributes(sspicon.SECPKG_ATTR_SIZES) sigsize = pkg_size_info['MaxSignature'] sigbuf = win32security.PySecBufferDescType() sigbuf.append(win32security.PySecBufferType(len(data), sspicon.SECBUFFER_DATA)) sigbuf.append(win32security.PySecBufferType(sigsize, sspicon.SECBUFFER_TOKEN)) sigbuf[0].Buffer = data self.ctxt.MakeSignature(0, sigbuf, self._get_next_seq_num()) return sigbuf[1].Buffer
'Verifies data and its signature. If verification fails, an sspi.error will be raised.'
def verify(self, data, sig):
sigbuf = win32security.PySecBufferDescType() sigbuf.append(win32security.PySecBufferType(len(data), sspicon.SECBUFFER_DATA)) sigbuf.append(win32security.PySecBufferType(len(sig), sspicon.SECBUFFER_TOKEN)) sigbuf[0].Buffer = data sigbuf[1].Buffer = sig self.ctxt.VerifySignature(sigbuf, self._get_next_seq_num())
'Return a suite of all tests cases contained in testCaseClass'
def loadTestsFromTestCase(self, testCaseClass):
leak_tests = [] for name in self.getTestCaseNames(testCaseClass): real_test = testCaseClass(name) leak_test = self._getTestWrapper(real_test) leak_tests.append(leak_test) return self.suiteClass(leak_tests)
'Called when an error has occurred. \'err\' is a tuple of values as returned by sys.exc_info().'
def addError(self, test, err):
import pywintypes exc_val = err[1] if (isinstance(exc_val, pywintypes.error) and (exc_val.winerror in non_admin_error_codes) and (not check_is_admin())): exc_val = TestSkipped(exc_val) elif (isinstance(exc_val, pywintypes.com_error) and (exc_val.hresult == winerror.CO_E_CLASSSTRING)): exc_val = TestSkipped(exc_val) elif isinstance(exc_val, NotImplementedError): exc_val = TestSkipped(NotImplementedError) if isinstance(exc_val, TestSkipped): reason = exc_val.args[0] try: reason = tuple(reason.args) except (AttributeError, TypeError): pass self.skips.setdefault(reason, 0) self.skips[reason] += 1 if self.showAll: self.stream.writeln(('SKIP (%s)' % (reason,))) elif self.dots: self.stream.write('S') self.stream.flush() return super(TestResult, self).addError(test, err)
'Test a long text field in excess of internal cursor data size (65536)'
def testLongVarchar(self):
self._test_val('longtextfield', ('abc' * 70000))
'Test a long raw field in excess of internal cursor data size (65536)'
def testLongBinary(self):
self._test_val('longbinaryfield', str2memory(('\x00\x01\x02' * 70000)))
'Test a unicode character that would be mangled if bound as plain character. For example, previously the below was returned as ascii \'a\''
def test_widechar(self):
self._test_val('username', u'\u0101')
'Accepts variable number of constant names that can be found in either win32security, ntsecuritycon, or winnt.'
def __init__(self, *const_names):
for const_name in const_names: try: const_val = getattr(win32security, const_name) except AttributeError: try: const_val = getattr(ntsecuritycon, const_name) except AttributeError: try: const_val = getattr(winnt, const_name) except AttributeError: raise AttributeError(('Constant "%s" not found in win32security, ntsecuritycon, or winnt.' % const_name)) setattr(self, const_name, const_val)
'Looks up the name of a particular value.'
def lookup_name(self, const_val):
for (k, v) in self.__dict__.iteritems(): if (v == const_val): return k raise AttributeError(('Value %s not found in enum' % const_val))
'Returns the names of all recognized flags in input, and any flags not found in the enum.'
def lookup_flags(self, flags):
flag_names = [] unknown_flags = flags for (k, v) in self.__dict__.iteritems(): if ((flags & v) == v): flag_names.append(k) unknown_flags = (unknown_flags & (~ v)) return (flag_names, unknown_flags)