Python win32api.error() Examples

The following are 30 code examples of win32api.error(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module win32api , or try the search function .
Example #1
Source File: winout.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def QueueIdleHandler(self,handler,count):
		try:
			bEmpty = self.QueueFlush(20)
			# If the queue is empty, then we are back to idle and restart interrupt logic.
			if bEmpty: self.interruptCount = 0
		except KeyboardInterrupt:
			# First interrupt since idle we just pass on.
			# later ones we dump the queue and give up.
			self.interruptCount = self.interruptCount + 1
			if self.interruptCount > 1:
				# Drop the queue quickly as the user is already annoyed :-)
				self.outputQueue = Queue.Queue(-1)
				print "Interrupted."
				bEmpty = 1
			else:
				raise # re-raise the error so the users exception filters up.
		return not bEmpty # More to do if not empty.

	# Returns true if the Window needs to be recreated. 
Example #2
Source File: TCP_generic.py    From XFLTReaT with MIT License 6 votes vote down vote up
def check(self):
		try:
			common.internal_print("Checking module on server: {0}".format(self.get_module_name()))

			server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			server_socket.settimeout(3)
			server_socket.connect((self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport"))))
			client_fake_thread = TCP_generic_thread(0, 0, None, None, server_socket, None, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name())
			client_fake_thread.do_check()
			client_fake_thread.communication(True)

			self.cleanup(server_socket)

		except socket.timeout:
			common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)
		except socket.error as exception:
			if exception.args[0] == 111:
				common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			else:
				common.internal_print("Connection error: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)

		return 
Example #3
Source File: win32timezone.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def _inDaylightSavings(self, dt):
		try:
			dstStart = self.GetDSTStartTime(dt.year)
			dstEnd = self.GetDSTEndTime(dt.year)
			
			if dstStart < dstEnd:
				inDaylightSavings = dstStart <= dt.replace(tzinfo=None) < dstEnd
			else:
				# in the southern hemisphere, daylight savings time
				#  typically ends before it begins in a given year.
				inDaylightSavings = not (dstEnd < dt.replace(tzinfo=None) <= dstStart)
		except ValueError:
			# there was an error parsing the time zone, which is normal when a
			#  start and end time are not specified.
			inDaylightSavings = False

		return inDaylightSavings 
Example #4
Source File: win32pdhquery.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def getinstpaths(self,object,counter,machine=None,objtype='Process',format = win32pdh.PDH_FMT_LONG):
		'''
		### Not an end-user function
		Calculate the paths for an instance object. Should alter
		to allow processing for lists of object-counter pairs.
		'''
		items, instances = win32pdh.EnumObjectItems(None,None,objtype, -1)
		# find out how many instances of this element we have...
		instances.sort()
		try:
			cur = instances.index(object)
		except ValueError:
			return [] # no instances of this object
		temp = [object]
		try:
			while instances[cur+1] == object:
				temp.append(object)
				cur = cur+1
		except IndexError: # if we went over the end
			pass
		paths = []
		for ind in range(len(temp)):
			# can this raise an error?
			paths.append(win32pdh.MakeCounterPath( (machine,'Process',object,None,ind,counter) ) )
		return paths # should also return the number of elements for naming purposes 
Example #5
Source File: win32pdhquery.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def collectdataslave(self,format = win32pdh.PDH_FMT_LONG):
		'''
		### 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.
		'''
		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) # a better way to signal failure???
			return temp
		except win32api.error: # will happen if, for instance, no counters are part of the query and we attempt to collect data for it.
			return [-1] * len(self.counters)
	# pickle functions 
Example #6
Source File: test_bits.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def JobError(self, job, error):
        print 'Job Error', job, error
        f = error.GetFile()
        print 'While downloading', f.GetRemoteName()
        print 'To', f.GetLocalName()
        print 'The following error happened:'
        self._print_error(error)
        if f.GetRemoteName().endswith('missing-favicon.ico'):
            print 'Changing to point to correct file'
            f2 = f.QueryInterface(bits.IID_IBackgroundCopyFile2)
            favicon = 'http://www.python.org/favicon.ico'
            print 'Changing RemoteName from', f2.GetRemoteName(), 'to', favicon
            f2.SetRemoteName(favicon)
            job.Resume()
        else:
            job.Cancel() 
Example #7
Source File: win32timezone.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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
	
	spec should be of the format @path,-stringID[;comment]
	see http://msdn2.microsoft.com/en-us/library/ms725481.aspx for details
	"""
	pattern = re.compile('@(?P<dllname>.*),-(?P<index>\d+)(?:;(?P<comment>.*))?')
	matcher = pattern.match(spec)
	assert matcher, 'Could not parse MUI spec'

	try:
		handle = DLLCache[matcher.groupdict()['dllname']]
		result = win32api.LoadString(handle, int(matcher.groupdict()['index']))
	except win32api.error, e:
		result = None 
Example #8
Source File: shell_view.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def _CreateMainWindow(self, prev, settings, browser, rect):
        # Creates a parent window that hosts the view window.  This window
        # gets the control notifications etc sent from the child.
        style = win32con.WS_CHILD | win32con.WS_VISIBLE #
        wclass_name = "ShellViewDemo_DefView"
        # Register the Window class.
        wc = win32gui.WNDCLASS()
        wc.hInstance = win32gui.dllhandle
        wc.lpszClassName = wclass_name
        wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW
        try:
            win32gui.RegisterClass(wc)
        except win32gui.error, details:
            # Should only happen when this module is reloaded
            if details[0] != winerror.ERROR_CLASS_ALREADY_EXISTS:
                raise 
Example #9
Source File: UDP_generic.py    From XFLTReaT with MIT License 6 votes vote down vote up
def connect(self):
		try:
			common.internal_print("Starting client: {0}".format(self.get_module_name()))
			server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			self.server_tuple = (self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport")))
			self.comms_socket = server_socket
			self.serverorclient = 0
			self.authenticated = False

			self.do_hello()
			self.communication(False)

		except KeyboardInterrupt:
			self.do_logoff()
			self.cleanup()
			raise
		except socket.error:
			self.cleanup()
			raise

		self.cleanup()

		return 
Example #10
Source File: install.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def CheckLoaderModule(dll_name):
    suffix = ""
    if is_debug_build: suffix = "_d"
    template = os.path.join(this_dir,
                            "PyISAPI_loader" + suffix + ".dll")
    if not os.path.isfile(template):
        raise ConfigurationError(
              "Template loader '%s' does not exist" % (template,))
    # We can't do a simple "is newer" check, as the DLL is specific to the
    # Python version.  So we check the date-time and size are identical,
    # and skip the copy in that case.
    src_stat = os.stat(template)
    try:
        dest_stat = os.stat(dll_name)
    except os.error:
        same = 0
    else:
        same = src_stat[stat.ST_SIZE]==dest_stat[stat.ST_SIZE] and \
               src_stat[stat.ST_MTIME]==dest_stat[stat.ST_MTIME]
    if not same:
        log(2, "Updating %s->%s" % (template, dll_name))
        shutil.copyfile(template, dll_name)
        shutil.copystat(template, dll_name)
    else:
        log(2, "%s is up to date." % (dll_name,)) 
Example #11
Source File: UDP_generic.py    From XFLTReaT with MIT License 6 votes vote down vote up
def check(self):
		try:
			common.internal_print("Checking module on server: {0}".format(self.get_module_name()))

			server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			self.server_tuple = (self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport")))
			self.comms_socket = server_socket
			self.serverorclient = 0
			self.authenticated = False

			self.do_check()
			self.communication(True)

		except KeyboardInterrupt:
			self.cleanup()
			raise
		except socket.timeout:
			common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
		except socket.error:
			self.cleanup()
			raise

		self.cleanup()

		return 
Example #12
Source File: codecontainer.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def GetName(self, dnt):
        name = self.module.__name__
        try:
            fname = win32api.GetFullPathName(self.module.__file__)
        except win32api.error:
            fname = self.module.__file__
        except AttributeError:
            fname = name
        if dnt==axdebug.DOCUMENTNAMETYPE_APPNODE:
            return name.split(".")[-1]
        elif dnt==axdebug.DOCUMENTNAMETYPE_TITLE:
            return fname
        elif dnt==axdebug.DOCUMENTNAMETYPE_FILE_TAIL:
            return os.path.split(fname)[1]
        elif dnt==axdebug.DOCUMENTNAMETYPE_URL:
            return "file:%s" % fname
        else:
            raise Exception(scode=winerror.E_UNEXPECTED) 
Example #13
Source File: cerapi.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def DumpRegistry(root, level=0):
    # A recursive dump of the remote registry to test most functions.
    h = wincerapi.CeRegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, None)
    level_prefix = " " * level
    index = 0
    # Enumerate values.
    while 1:
        try:
            name, data, typ = wincerapi.CeRegEnumValue(root, index)
        except win32api.error:
            break
        print "%s%s=%s" % (level_prefix, name, repr(str(data)))
        index = index+1
    # Now enumerate all keys.
    index=0
    while 1:
        try:
            name, klass = wincerapi.CeRegEnumKeyEx(root, index)
        except win32api.error:
            break
        print "%s%s\\" % (level_prefix, name)
        subkey = wincerapi.CeRegOpenKeyEx(root, name)
        DumpRegistry(subkey, level+1)
        index = index+1 
Example #14
Source File: socket_server.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def verify_request(self, sock, ca):
        # Do the sspi auth dance
        self.sa.reset()
        while 1:
            data = _get_msg(sock)
            if data is None:
                return False
            try:
                err, sec_buffer = self.sa.authorize(data)
            except sspi.error, details:
                print "FAILED to authorize client:", details
                return False
                
            if err==0:
                break
            _send_msg(sock, sec_buffer[0].Buffer) 
Example #15
Source File: browseProjects.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def GetSubList(self):
		keyStr = regutil.BuildDefaultPythonKey() + "\\PythonPath"
		hKey = win32api.RegOpenKey(regutil.GetRootKey(), keyStr)
		try:
			ret = []
			ret.append(HLIProjectRoot("", "Standard Python Library")) # The core path.
			index = 0
			while 1:
				try:
					ret.append(HLIProjectRoot(win32api.RegEnumKey(hKey, index)))
					index = index + 1
				except win32api.error:
					break
			return ret
		finally:
			win32api.RegCloseKey(hKey) 
Example #16
Source File: document.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def Run(self):
		while 1:
			handles = [self.stopEvent, self.adminEvent]
			if self.watchEvent is not None:
				handles.append(self.watchEvent)
			rc = win32event.WaitForMultipleObjects(handles, 0, win32event.INFINITE)
			if rc == win32event.WAIT_OBJECT_0:
				break
			elif rc == win32event.WAIT_OBJECT_0+1:
				self.RefreshEvent()
			else:
				win32api.PostMessage(self.hwnd, MSG_CHECK_EXTERNAL_FILE, 0, 0)
				try:
					# If the directory has been removed underneath us, we get this error.
					win32api.FindNextChangeNotification(self.watchEvent)
				except win32api.error, exc:
					print "Can not watch file", self.doc.GetPathName(), "for changes -", exc.strerror
					break

		# close a circular reference 
Example #17
Source File: regedit.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def UpdateForRegItem(self, item):
		self.DeleteAllItems()
		hkey = win32api.RegOpenKey(item.keyRoot, item.keyName)
		try:
			valNum = 0
			ret = []
			while 1:
				try:
					res = win32api.RegEnumValue(hkey, valNum)
				except win32api.error:
					break
				name = res[0]
				if not name: name = "(Default)"
				self.InsertItem(valNum, name)
				self.SetItemText(valNum, 1, str(res[1]))
				valNum = valNum + 1
		finally:
			win32api.RegCloseKey(hkey) 
Example #18
Source File: regedit.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def GetSubList(self):
		hkey = win32api.RegOpenKey(self.keyRoot, self.keyName)
		win32ui.DoWaitCursor(1)
		try:
			keyNum = 0
			ret = []
			while 1:
				try:
					key = win32api.RegEnumKey(hkey, keyNum)
				except win32api.error:
					break
				ret.append(HLIRegistryKey(self.keyRoot, self.keyName + "\\" + key, key))
				keyNum = keyNum + 1
		finally:
			win32api.RegCloseKey(hkey)
			win32ui.DoWaitCursor(0)
		return ret 
Example #19
Source File: app.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def OnUpdatePosIndicator(self, cmdui):
		editControl = scriptutils.GetActiveEditControl()
		value = " " * 5
		if editControl is not None:
			try:
				startChar, endChar = editControl.GetSel()
				lineNo = editControl.LineFromChar(startChar)
				colNo = endChar - editControl.LineIndex(lineNo)

				if cmdui.m_nID==win32ui.ID_INDICATOR_LINENUM:
					value = "%0*d" % (5, lineNo + 1)
				else:
					value = "%0*d" % (3, colNo + 1)
			except win32ui.error:
				pass
		cmdui.SetText(value)
		cmdui.Enable() 
Example #20
Source File: app.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def OnHelp(self,id, code):
		try:
			if id==win32ui.ID_HELP_GUI_REF:
				helpFile = regutil.GetRegisteredHelpFile("Pythonwin Reference")
				helpCmd = win32con.HELP_CONTENTS
			else:
				helpFile = regutil.GetRegisteredHelpFile("Main Python Documentation")
				helpCmd = win32con.HELP_FINDER
			if helpFile is None:
				win32ui.MessageBox("The help file is not registered!")
			else:
				import help
				help.OpenHelpFile(helpFile, helpCmd)
		except:
			t, v, tb = sys.exc_info()
			win32ui.MessageBox("Internal error in help file processing\r\n%s: %s" % (t,v))
			tb = None # Prevent a cycle 
Example #21
Source File: document.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def _UpdateUIForState(self):
		"""Change the title to reflect the state of the document - 
		eg ReadOnly, Dirty, etc
		"""
		filename = self.GetPathName()
		if not filename: return # New file - nothing to do
		try:
			# This seems necessary so the internal state of the window becomes
			# "visible".  without it, it is still shown, but certain functions
			# (such as updating the title) dont immediately work?
			self.GetFirstView().ShowWindow(win32con.SW_SHOW)
			title = win32ui.GetFileTitle(filename)
		except win32ui.error:
			title = filename
		if self._IsReadOnly():
			title = title + " (read-only)"
		self.SetTitle(title) 
Example #22
Source File: document.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def _DocumentStateChanged(self):
		"""Called whenever the documents state (on disk etc) has been changed
		by the editor (eg, as the result of a save operation)
		"""
		if self.GetPathName():
			try:
				self.fileStat = os.stat(self.GetPathName())
			except os.error:
				self.fileStat = None
		else:
			self.fileStat = None
		self.watcherThread._DocumentStateChanged()
		self._UpdateUIForState()
		self._ApplyOptionalToViews("_UpdateUIForState")
		self._ApplyOptionalToViews("SetReadOnly", self._IsReadOnly())
		self._ApplyOptionalToViews("SCISetSavePoint")
		# Allow the debugger to reset us too.
		import pywin.debugger
		if pywin.debugger.currentDebugger is not None:
			pywin.debugger.currentDebugger.UpdateDocumentLineStates(self)
			
	# Read-only document support - make it obvious to the user
	# that the file is read-only. 
Example #23
Source File: scriptutils.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def _HandlePythonFailure(what, syntaxErrorPathName = None):
	typ, details, tb = sys.exc_info()
	if isinstance(details, SyntaxError):
		try:
			msg, (fileName, line, col, text) = details
			if (not fileName or fileName =="<string>") and syntaxErrorPathName:
				fileName = syntaxErrorPathName
			_JumpToPosition(fileName, line, col)
		except (TypeError, ValueError):
			msg = str(details)
		win32ui.SetStatusText('Failed to ' + what + ' - syntax error - %s' % msg)
	else:	
		traceback.print_exc()
		win32ui.SetStatusText('Failed to ' + what + ' - ' + str(details) )
	tb = None # Clean up a cycle.

# Find the Python TabNanny in either the standard library or the Python Tools/Scripts directory. 
Example #24
Source File: TCP_generic.py    From XFLTReaT with MIT License 6 votes vote down vote up
def send(self, channel_type, message, additional_data):
		if channel_type == common.CONTROL_CHANNEL_BYTE:
			transformed_message = self.transform(self.encryption, common.CONTROL_CHANNEL_BYTE+message, 1)
		else:
			transformed_message = self.transform(self.encryption, common.DATA_CHANNEL_BYTE+message, 1)

		common.internal_print("{0} sent: {1}".format(self.module_short, len(transformed_message)), 0, self.verbosity, common.DEBUG)

		# WORKAROUND?!
		# Windows: It looks like when the buffer fills up the OS does not do
		# congestion control, instead throws and exception/returns with
		# WSAEWOULDBLOCK which means that we need to try it again later.
		# So we sleep 100ms and hope that the buffer has more space for us.
		# If it does then it sends the data, otherwise tries it in an infinite
		# loop...
		while True:
			try:
				return self.comms_socket.send(struct.pack(">H", len(transformed_message))+transformed_message)
			except socket.error as se:
				if se.args[0] == 10035: # WSAEWOULDBLOCK
					time.sleep(0.1)
					pass
				else:
					raise 
Example #25
Source File: toolmenu.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def OnButtonMove(self, id, cmd):
		if cmd==win32con.BN_CLICKED:
			try:
				itemNo = self.listControl.GetNextItem(-1, commctrl.LVNI_SELECTED)
			except win32ui.error:
				return
			menu = self.listControl.GetItemText(itemNo, 0)
			cmd = self.listControl.GetItemText(itemNo, 1)
			if id == win32ui.IDC_BUTTON1:
				# Move up
				if itemNo > 0:
					self.listControl.DeleteItem(itemNo)
					# reinsert it.
					self.listControl.InsertItem(itemNo-1, menu)
					self.listControl.SetItemText(itemNo-1, 1, cmd)
			else:
				# Move down.
				if itemNo < self.listControl.GetItemCount()-1:
					self.listControl.DeleteItem(itemNo)
					# reinsert it.
					self.listControl.InsertItem(itemNo+1, menu)
					self.listControl.SetItemText(itemNo+1, 1, cmd) 
Example #26
Source File: winout.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def HandleSpecialLine(self):
		import scriptutils
		line = self.GetLine()
		if line[:11]=="com_error: ":
			# An OLE Exception - pull apart the exception
			# and try and locate a help file.
			try:
				import win32api, win32con
				det = eval(line[line.find(":")+1:].strip())
				win32ui.SetStatusText("Opening help file on OLE error...");
				import help
				help.OpenHelpFile(det[2][3],win32con.HELP_CONTEXT, det[2][4])
				return 1
			except win32api.error, details:
				win32ui.SetStatusText("The help file could not be opened - %s" % details.strerror)
				return 1
			except: 
Example #27
Source File: toolmenu.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def WriteToolMenuItems( items ):
	# Items is a list of (menu, command)
	# Delete the entire registry tree.
	try:
		mainKey = win32ui.GetAppRegistryKey()
		toolKey = win32api.RegOpenKey(mainKey, "Tools Menu")
	except win32ui.error:
		toolKey = None
	if toolKey is not None:
		while 1:
			try:
				subkey = win32api.RegEnumKey(toolKey, 0)
			except win32api.error:
				break
			win32api.RegDeleteKey(toolKey, subkey)
	# Keys are now removed - write the new ones.
	# But first check if we have the defaults - and if so, dont write anything!
	if items==defaultToolMenuItems:
		return
	itemNo = 1
	for menu, cmd in items:
		win32ui.WriteProfileVal("Tools Menu\\%s" % itemNo, "", menu)
		win32ui.WriteProfileVal("Tools Menu\\%s" % itemNo, "Command", cmd)
		itemNo = itemNo + 1 
Example #28
Source File: winout.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def HandleOutput(self,message):
#		debug("QueueOutput on thread %d, flags %d with '%s'...\n" % (win32api.GetCurrentThreadId(), self.writeQueueing, message ))
		self.outputQueue.put(message)
		if win32api.GetCurrentThreadId() != self.mainThreadId:
			pass
#			debug("not my thread - ignoring queue options!\n")
		elif self.writeQueueing==flags.WQ_LINE:
			pos = message.rfind('\n')
			if pos>=0:
#				debug("Line queueing - forcing flush\n")
				self.QueueFlush()
				return
		elif self.writeQueueing==flags.WQ_NONE:
#			debug("WQ_NONE - flushing!\n")
			self.QueueFlush()
			return
		# Let our idle handler get it - wake it up
		try:
			win32ui.GetMainFrame().PostMessage(win32con.WM_USER) # Kick main thread off.
		except win32ui.error:
			# This can happen as the app is shutting down, so we send it to the C++ debugger
			win32api.OutputDebugString(message)

	# delegate certain fns to my view. 
Example #29
Source File: win32pdhquery.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def open(self,*args,**namedargs):
		'''
		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.
		'''
		# do all the normal opening stuff, self._base is now the query object
		BaseQuery.open(*(self,)+args, **namedargs)
		# should rewrite getinstpaths to take a single tuple
		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) # if we fail on the line above, this path won't be in the table or the counters
			except win32api.error:
				pass # again, what to do with a malformed path??? 
Example #30
Source File: document.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def OnSaveDocument( self, fileName ):
		win32ui.SetStatusText("Saving file...",1)
		# rename to bak if required.
		dir, basename = os.path.split(fileName)
		if self.bakFileType==BAK_DOT_BAK:
			bakFileName=dir+'\\'+os.path.splitext(basename)[0]+'.bak'
		elif self.bakFileType==BAK_DOT_BAK_TEMP_DIR:
			bakFileName=win32api.GetTempPath()+'\\'+os.path.splitext(basename)[0]+'.bak'
		elif self.bakFileType==BAK_DOT_BAK_BAK_DIR:
			tempPath=os.path.join(win32api.GetTempPath(),'bak')
			try:
				os.mkdir(tempPath,0)
			except os.error:
				pass
			bakFileName=os.path.join(tempPath,basename)
		try:
			os.unlink(bakFileName)	# raise NameError if no bakups wanted.
		except (os.error, NameError):
			pass
		try:
			# Do a copy as it might be on different volumes,
			# and the file may be a hard-link, causing the link
			# to follow the backup.
			shutil.copy2(fileName, bakFileName)
		except (os.error, NameError, IOError):
			pass
		try:
			self.SaveFile(fileName)
		except IOError, details:
			win32ui.MessageBox("Error - could not save file\r\n\r\n%s"%details)
			return 0