def __init__(self, str, recurse=0): dp = string.split(str, ';') dirs = {} for d in dp: if os.path.isdir(d): d = string.lower(d) if not dirs.has_key(d): dirs[d] = None if recurse: subdirs = getsubdirs(d) for sd in subdirs: sd = string.lower(sd) if not dirs.has_key(sd): dirs[sd] = None elif os.path.isfile(d): pass else: x = None if os.environ.has_key(d): x = dirpath(os.environ[d]) elif d[:5] == 'HKEY_': keystr = string.split(d, '\\') try: root = eval('win32con.' + keystr[0]) except: win32ui.MessageBox( "Can't interpret registry key name '%s'" % keystr[0]) try: subkey = string.join(keystr[1:], '\\') val = win32api.RegQueryValue(root, subkey) if val: x = dirpath(val) else: win32ui.MessageBox( "Registry path '%s' did not return a path entry" % d) except: win32ui.MessageBox( "Can't interpret registry key value: %s" % keystr[1:]) else: win32ui.MessageBox("Directory '%s' not found" % d) if x: for xd in x: if not dirs.has_key(xd): dirs[xd] = None if recurse: subdirs = getsubdirs(xd) for sd in subdirs: sd = string.lower(sd) if not dirs.has_key(sd): dirs[sd] = None self.dirs = [] for d in dirs.keys(): self.dirs.append(d)
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 as details: win32ui.MessageBox("Error - could not save file\r\n\r\n%s"%details) return 0 except (UnicodeEncodeError, LookupError) as details: rc = win32ui.MessageBox("Encoding failed: \r\n%s"%details + '\r\nPlease add desired source encoding as first line of file, eg \r\n' + '# -*- coding: mbcs -*-\r\n\r\n' + 'If you continue, the file will be saved as binary and will\r\n' + 'not be valid in the declared encoding.\r\n\r\n' + 'Save the file as binary with an invalid encoding?', "File save failed", win32con.MB_YESNO | win32con.MB_DEFBUTTON2) if rc==win32con.IDYES: try: self.SaveFile(fileName, encoding="latin-1") except IOError as details: win32ui.MessageBox("Error - could not save file\r\n\r\n%s"%details) return 0 else: return 0 self.SetModifiedFlag(0) # No longer dirty self.bDeclinedReload = 0 # They probably want to know if it changes again! win32ui.AddToRecentFileList(fileName) self.SetPathName(fileName) win32ui.SetStatusText("Ready") self._DocumentStateChanged() return 1
def check(): server = NewConn.getitem('_server') port = NewConn.getitem('_port') NewConn.GetDBList() if str(NewConn.getitem('_running')) == 'False': win32ui.MessageBox("No server running on host "+ server+" at port "+str(port), "Server Connection", flag_excl) return False if str(NewConn.getitem('_login')) == 'False': win32ui.MessageBox("Please login to the database first", "Database Connection", flag_excl) return False return True
def NeedApp(): import win32ui rc = win32ui.MessageBox(NeedAppMsg % sys.argv[0], "Demos", win32con.MB_YESNO) if rc == win32con.IDYES: try: parent = win32ui.GetMainFrame().GetSafeHwnd() win32api.ShellExecute(parent, None, 'pythonwin.exe', '/app "%s"' % sys.argv[0], None, 1) except win32api.error as details: win32ui.MessageBox("Error executing command - %s" % (details), "Demos")
def SearchObjectsForText(btnProcessor,*args): #Check if server running or user logged in b = check() if not b: return search_txt = win32gui.GetDlgItemText(btnProcessor.window.hwnd, btnProcessor.other_ids[0]) if not search_txt: win32ui.MessageBox("Enter text to search for", "", flag_info) return # Get titles from list obj_titles=[] for ch in hwndChk_list: id = ch[0] hwnd = ch[1] chk = win32gui.SendMessage(hwnd, win32con.BM_GETCHECK) if chk: txt = win32gui.GetDlgItemText(btnProcessor.window.hwnd,id) obj_titles.append(txt) # Prepare list of objects to search for the seach_keyword obj_list = btnProcessor.window.manager.config['objects'] search_list = [] try: all_obj_list = NewConn.GetAllObjects() for title in obj_titles: objname = [obj[1] for obj in obj_list if obj[0] == title] if objname: assert len(objname) == 1 if objname[0] in all_obj_list: search_list.append(objname[0]) else: win32ui.MessageBox("Module %s (%s) not installed. Please install it." \ %(title,objname[0]), "", flag_excl) return # Get the records by searching the objects in search_list for the search_keyword as objects_with_match global objects_with_match list_hwnd = win32gui.GetDlgItem(btnProcessor.window.hwnd, btnProcessor.other_ids[1]) if search_list: objects_with_match = NewConn.GetObjectItems(search_list, search_txt) if not objects_with_match: win32ui.MessageBox("No matching records found in checked objects", "", flag_info) else: win32ui.MessageBox("No object selected", "", flag_info) objects_with_match=[] # Display the objects_with_match records in list setList(list_hwnd) except Exception,e: msg=getMessage(e) win32ui.MessageBox(msg, "", flag_error)
def EditValue(self, item): # Edit the current value class EditDialog(dialog.Dialog): def __init__(self, item): self.item = item dialog.Dialog.__init__(self, win32ui.IDD_LARGE_EDIT) def OnInitDialog(self): self.SetWindowText("Enter new value") self.GetDlgItem(win32con.IDCANCEL).ShowWindow(win32con.SW_SHOW) self.edit = self.GetDlgItem(win32ui.IDC_EDIT1) # Modify the edit windows style style = win32api.GetWindowLong( self.edit.GetSafeHwnd(), win32con.GWL_STYLE) style = style & (~win32con.ES_WANTRETURN) win32api.SetWindowLong( self.edit.GetSafeHwnd(), win32con.GWL_STYLE, style) self.edit.SetWindowText(str(self.item)) self.edit.SetSel(-1) return dialog.Dialog.OnInitDialog(self) def OnDestroy(self, msg): self.newvalue = self.edit.GetWindowText() try: index = self.GetNextItem(-1, commctrl.LVNI_SELECTED) except win32ui.error: return # No item selected. if index == 0: keyVal = "" else: keyVal = self.GetItemText(index, 0) # Query for a new value. try: newVal = self.GetItemsCurrentValue(item, keyVal) except TypeError as details: win32ui.MessageBox(details) return d = EditDialog(newVal) if d.DoModal() == win32con.IDOK: try: self.SetItemsCurrentValue(item, keyVal, d.newvalue) except win32api.error as exc: win32ui.MessageBox( "Error setting value\r\n\n%s" % exc.strerror) self.UpdateForRegItem(item)
def TestConnection(btnProcessor,*args): server = NewConn.getitem('_server') port = NewConn.getitem('_port') NewConn.GetDBList() if str(NewConn.getitem('_running')) == 'False': btnProcessor.window.LoadAllControls() win32ui.MessageBox("No server running on host "+ server+" at port "+str(port), "Server Connection", flag_excl) return try: dbname = win32gui.GetDlgItemText(btnProcessor.window.hwnd, 7000) if not dbname: win32ui.MessageBox("Please enter database name", "", flag_excl) return except Exception,e: dbname = win32gui.GetDlgItemText(btnProcessor.window.hwnd, btnProcessor.other_ids[0]) if not dbname: win32ui.MessageBox("No database found on host "+ server+" at port "+str(port), "Database Connection", flag_excl) return uname = win32gui.GetDlgItemText(btnProcessor.window.hwnd, btnProcessor.other_ids[1]) pwd = win32gui.GetDlgItemText(btnProcessor.window.hwnd, btnProcessor.other_ids[2]) if not uname: win32ui.MessageBox("Enter Username", "", flag_excl) return if not pwd: win32ui.MessageBox("Enter Password", "", flag_excl) return #Establish Connection try: uid = NewConn.login(dbname, uname, pwd) if uid: msg = "Connection Successful" NewConn.setitem('_login', 'True') NewConn.setitem('_uname', uname) NewConn.setitem('_pwd', pwd) NewConn.setitem('_uid', uid) flag = flag_info if not NewConn.IsCRMInstalled(): msg+= '\n\n'+" 'CRM' module is not installed. So CRM cases cannot be created." NewConn.setitem('_iscrm', False) else: try: list = NewConn.GetCSList() NewConn.setitem('_iscrm', True) except Exception,e: msg+= '\n\n'+"CRM cases cannot be created.\n\n" + getMessage(e) NewConn.setitem('_iscrm', False) else:
class CountryComboProcessor(ComboProcessor): def Init(self): self.UpdateControl_FromValue() def UpdateControl_FromValue(self): from manager import ustr import win32ui combo = self.GetControl() conn = self.func() win32gui.SendMessage(combo, win32con.CB_RESETCONTENT, 0, 0) id_list = {} state_list = [] try: country_list = list(conn.GetAllCountry()) for item in country_list: win32gui.SendMessage(combo, win32con.CB_ADDSTRING, 0, ustr(item[1]).encode('iso-8859-1')) win32gui.SendMessage(combo, win32con.CB_SETCURSEL, -1, 0) cnt = win32gui.SendMessage(combo, win32con.CB_GETCOUNT, 0, 0) return except xmlrpclib.Fault, e: msg = str(e.faultCode) or e.faultString or e.message or str(e) win32ui.MessageBox(msg, "Open Partner") except Exception, e: win32ui.MessageBox(str(e), "Open Partner")
def MakeAttachment(btnProcessor,*args): #Check if server running or user logged in b = check() if not b: return ex = btnProcessor.window.manager.outlook.ActiveExplorer() assert ex.Selection.Count == 1 mail = ex.Selection.Item(1) mail = GetMail(btnProcessor) #get selected records hwndList = win32gui.GetDlgItem(btnProcessor.window.hwnd, btnProcessor.other_ids[0]) r = GetSelectedItems(hwndList) if not r: win32ui.MessageBox("No records selected", "Make Attachment", flag_info) return try: NewConn.ArchiveToOpenERP(r,mail) msg="Mail archived to OpenERP." flag = flag_info except Exception,e: msg = "Attachment not created \n\n" + getMessage(e) flag = flag_error
def NeedGoodGUI(): from pywin.framework.app import HaveGoodGUI rc = HaveGoodGUI() if not rc: win32ui.MessageBox(NeedGUIMsg, "Demos") return rc
def verify_config(config): sections = ['thermostat', 'microcontroller', 'probe'] types = ["cpu", "ram", "gpu", "mobo", "disk"] if not all(config.has_section(s) for s in sections): log.error("Config file 'thermostat.ini' not found; creating a new one.") config['thermostat'] = { "12V": "60", "5V": "45", "0V": "0", "reverse_hysteresis": "5" } config['microcontroller'] = { "vid": "0x16C0", "pid": "0x0486" } config['probe'] = dict({ "device": "Intel Core i7-6600U", "sensor": "CPU Package" },**dict((t, "false" if t != "cpu" else "true") for t in types)) with open('thermostat.ini', 'w') as configfile: config.write(configfile) win32ui.MessageBox("Config file 'thermostat.ini' not found. A new one has been created", "Startup Error", win32con.MB_ICONERROR) sys.exit(1)
def handle_user_input(self): """ :return: does what the client asks for """ done = False # checks for requests while was down message = self.username + SEPERATOR + GET_REQUESTS self.send_request_to_server(self.my_socket, message) requests = self.read_server_response(self.my_socket) if requests.decode() != NO_REQUESTS and requests.decode( ) != SERVER_FELL: self.answer_all(requests.decode()) # while the operation is not quit. if quit - go out while not done: # if not blank command # sends the operation to the server data = self.read_server_response(self.my_socket) if data is not None: if data.decode() == READY: data = self.upload(self.request, self.my_socket) self.handle_server_response(data) if data.decode() == SERVER_FELL: win32ui.MessageBox("The Server Has Fallen Down", "Error At Cloud", win32con.MB_YESNOCANCEL) self.my_socket.close() try: self.req_socket.close() except: pass # is the mode doesn't include a receiving socket self.client_reg.set_observer( DENY_OBS) # so that folder manager will not be triggered done = True
def OnViewBrowse(self, id, code): " Called when ViewBrowse message is received " 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')
def askinteger(self, caption, prompt, parent=None, initialvalue=0, minvalue=None, maxvalue=None): while 1: rc = GetSimpleInput(prompt, str(initialvalue), caption) if rc is None: return 0 # Correct "cancel" semantics? err = None try: rc = int(rc) except ValueError: err = "Please enter an integer" if not err and minvalue is not None and rc < minvalue: err = "Please enter an integer greater then or equal to %s" % ( minvalue, ) if not err and maxvalue is not None and rc > maxvalue: err = "Please enter an integer less then or equal to %s" % ( maxvalue, ) if err: win32ui.MessageBox(err, caption, win32con.MB_OK) continue return rc
def CheckExternalDocumentUpdated(self): if self.bDeclinedReload or not self.GetPathName(): return try: newstat = os.stat(self.GetPathName()) except os.error as exc: if not self.bReportedFileNotFound: print("The file '%s' is open for editing, but\nchecking it for changes caused the error: %s" % (self.GetPathName(), exc.strerror)) self.bReportedFileNotFound = 1 return if self.bReportedFileNotFound: print("The file '%s' has re-appeared - continuing to watch for changes..." % (self.GetPathName(),)) self.bReportedFileNotFound = 0 # Once found again we want to start complaining. changed = (self.fileStat is None) or \ self.fileStat[0] != newstat[0] or \ self.fileStat[6] != newstat[6] or \ self.fileStat[8] != newstat[8] or \ self.fileStat[9] != newstat[9] if changed: question = None if self.IsModified(): question = "%s\r\n\r\nThis file has been modified outside of the source editor.\r\nDo you want to reload it and LOSE THE CHANGES in the source editor?" % self.GetPathName() mbStyle = win32con.MB_YESNO | win32con.MB_DEFBUTTON2 # Default to "No" else: if not self.bAutoReload: question = "%s\r\n\r\nThis file has been modified outside of the source editor.\r\nDo you want to reload it?" % self.GetPathName() mbStyle = win32con.MB_YESNO # Default to "Yes" if question: rc = win32ui.MessageBox(question, None, mbStyle) if rc!=win32con.IDYES: self.bDeclinedReload = 1 return self.ReloadDocument()
def OnOpenDocument(self, filename): # init data members #print "Opening", filename self.SetPathName(filename) # Must set this early! try: if is_platform_unicode: # Scintilla in UTF-8 mode - translate accordingly. import codecs f = codecs.open(filename, 'rb', default_platform_encoding) else: f = open(filename, 'rb') try: text = f.read() finally: f.close() if is_platform_unicode: # Translate from locale-specific (MCBS) encoding to UTF-8 for Scintilla text = text.encode(default_scintilla_encoding) except IOError: win32ui.MessageBox("Could not load the file from %s" % filename) return 0 self._SetLoadedText(text) ## if self.GetFirstView(): ## self.GetFirstView()._SetLoadedText(text) ## self.SetModifiedFlag(0) # No longer dirty return 1
def OnFileLocate(self, id, code): from pywin.mfc import dialog import scriptutils import os global lastLocateFileName # save the new version away for next time... # Loop until a good name, or cancel while 1: name = dialog.GetSimpleInput('File name', lastLocateFileName, 'Locate Python File') if name is None: # Cancelled. break lastLocateFileName = name # if ".py" supplied, rip it off! if string.lower(lastLocateFileName[-3:]) == '.py': lastLocateFileName = lastLocateFileName[:-3] lastLocateFileName = string.translate(lastLocateFileName, string.maketrans(".", "\\")) newName = scriptutils.LocatePythonFile(lastLocateFileName) if newName is None: win32ui.MessageBox("The file '%s' can not be located" % lastLocateFileName) else: win32ui.GetApp().OpenDocumentFile(newName) break
def open_file(): #创建 tkinter顶层容器 root = tkinter.Tk() #顶层容器标题 root.title('test') #创建一个框器(也是一个容器) f = tkinter.Frame(root, width=10) f.pack() win32ui.MessageBox('请选择文件') # 使用tkinter库中的filedialog类的askdirectroy()方法 dialog = filedialog.askdirectory(initialdir=r'C:\Users\HP\Desktop', mustexist=False, parent=f, title='Please select directory') #打印选择的文件名 print(dialog) #销毁容器 root.destroy() print(os.listdir(dialog)) print('11111111111') for file in os.listdir(dialog): if file.endswith(".xlsx") or file.endswith('.xls'): filepath = os.path.join(dialog, file) filesize = round(os.path.getsize(filepath) / 1024) print(file + ' 大小:' + str(filesize) + 'KB') excel_open(filepath)
def ArchiveToOpenERP(self, recs, mail): import win32ui, win32con conn = xmlrpclib.ServerProxy(self._uri + '/xmlrpc/object') import eml eml_path = eml.generateEML(mail) att_name = ustr(eml_path.split('\\')[-1]) cnt = 1 for rec in recs: #[('res.partner', 3, 'Agrolait')] cnt += 1 obj = rec[0] obj_id = rec[1] ids = execute(conn, 'execute', self._dbname, int(self._uid), self._pwd, 'ir.attachment', 'search', [('res_id', '=', obj_id), ('name', '=', att_name)]) if ids: name = execute(conn, 'execute', self._dbname, int(self._uid), self._pwd, obj, 'read', obj_id, ['name'])['name'] msg = "This mail is already attached to object with name '%s'" % name win32ui.MessageBox(msg, "Make Attachment", win32con.MB_ICONINFORMATION) continue sub = ustr(mail.Subject) if len(sub) > 60: l = 60 - len(sub) sub = sub[0:l] res = {} res['res_model'] = obj content = "".join(open(eml_path, "r").readlines()).encode('base64') res['name'] = att_name res['datas_fname'] = sub + ".eml" res['datas'] = content res['res_id'] = obj_id execute(conn, 'execute', self._dbname, int(self._uid), self._pwd, 'ir.attachment', 'create', res)
def UpdateControl_FromValue(self): combo = self.GetControl() conn = self.func() if str(conn.getitem('_iscrm')) == 'False': win32gui.EnableWindow(combo, False) return try: list = [ 'CRM Lead' ] #, 'CRM Helpdesk', 'CRM Lead', 'CRM Meeting', 'CRM Opportunity', 'CRM Phonecall'] objlist = conn.GetAllObjects() if 'crm.claim' in objlist: list.append('CRM Claim') if 'crm.helpdesk' in objlist: list.append('CRM Helpdesk') if 'crm.fundraising' in objlist: list.append('CRM Fundraising') if 'hr.applicant' in objlist: list.append('HR Applicant') if 'project.issue' in objlist: list.append('Project Issue') win32gui.SendMessage(combo, win32con.CB_RESETCONTENT, 0, 0) for item in list: win32gui.SendMessage(combo, win32con.CB_ADDSTRING, 0, str(item)) win32gui.SendMessage(combo, win32con.CB_SETCURSEL, 0, 0) return except xmlrpclib.Fault, e: win32ui.MessageBox(str(e.faultCode), "CRM Case", win32con.MB_ICONEXCLAMATION)
def caught(event): global intrusion, policy, randdrop print "Quack! Quack! -- Time to go Duckhunting!" intrusion = True #Paranoid Policy if (policy == "paranoid"): win32ui.MessageBox( "Someone might be trying to inject keystrokes into your computer.\nPlease check your ports or any strange programs running.\nEnter your Password to unlock keyboard.", "KeyInjection Detected", 4096) # MB_SYSTEMMODAL = 4096 -- Always on top. return False #Sneaky Policy elif (policy == "sneaky"): randdrop += 1 #Drop every 5th letter if (randdrop == 7): randdrop = 0 return False else: return True #Logging Only Policy elif (policy == "log"): log(event) return True #Normal Policy log(event) return False
def FindVssProjectInfo(fullfname): """Looks up the file system for an INI file describing the project. Looking up the tree is for ni style packages. Returns (projectName, pathToFileName) where pathToFileName contains the path from the ini file to the actual file. """ path, fnameonly = os.path.split(fullfname) origPath = path project = "" retPaths = [fnameonly] while not project: iniName = os.path.join(path, g_iniName) database = win32api.GetProfileVal("Python", "Database", "", iniName) project = win32api.GetProfileVal("Python", "Project", "", iniName) if project: break # No valid INI file in this directory - look up a level. path, addpath = os.path.split(path) if not addpath: # Root? break retPaths.insert(0, addpath) if not project: win32ui.MessageBox( "%s\r\n\r\nThis directory is not configured for Python/VSS" % origPath) return return project, "/".join(retPaths), database
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
def ArchiveToOpenERP(self, recs, mail): import win32con import win32ui conn = xmlrpclib.ServerProxy(self._uri + '/xmlrpc/object') flag = False new_msg = ext_msg ="" message_id = referances = None try: session = win32com.client.Dispatch("MAPI.session") session.Logon('Outlook') objMessage = session.GetMessage(mail.EntryID, mail.Parent.StoreID) objFields = objMessage.Fields strheader = objFields.Item(mapitags.PR_TRANSPORT_MESSAGE_HEADERS) strheader = ustr(strheader).encode('iso-8859-1') headers = {} strheader = strheader.replace("\n ", " ").splitlines() for line in strheader: split_here = line.find(":") headers[line[:split_here]] = line[split_here:] temp1 = headers.get('Message-ID') temp2 = headers.get('Message-Id') referances = headers.get('References') if temp1 == None: message_id = temp2 if temp2 == None: message_id = temp1 startCut = message_id.find("<") endCut = message_id.find(">") message_id = message_id[startCut:endCut+1] if not referances == None: startCut = referances.find("<") endCut = referances.find(">") referances = referances[startCut:endCut+1] except Exception,e: win32ui.MessageBox(str(e),"Archive To OpenERP") return
def RunTabNanny(filename): import cStringIO tabnanny = FindTabNanny() if tabnanny is None: win32ui.MessageBox("The TabNanny is not around, so the children can run amok!" ) return # Capture the tab-nanny output newout = cStringIO.StringIO() old_out = sys.stderr, sys.stdout sys.stderr = sys.stdout = newout try: tabnanny.check(filename) finally: # Restore output sys.stderr, sys.stdout = old_out data = newout.getvalue() if data: try: lineno = string.split(data)[1] lineno = int(lineno) _JumpToPosition(filename, lineno) try: # Try and display whitespace GetActiveEditControl().SCISetViewWS(1) except: pass win32ui.SetStatusText("The TabNanny found trouble at line %d" % lineno) except (IndexError, TypeError, ValueError): print "The tab nanny complained, but I cant see where!" print data return 0 return 1
def OnClicked(self, id): server = win32gui.GetDlgItemText(self.window.hwnd, self.other_ids[0]) try: port = int(win32gui.GetDlgItemText(self.window.hwnd, self.other_ids[1])) except ValueError, e: win32ui.MessageBox("Port should be an integer", "Error", flag_excl) return
def MakeNewBuildNo(project, buildDesc=None, auto=0, bRebrand=0): if buildDesc is None: buildDesc = "Created by Python" ss = GetSS() i = ss.VSSItem(project) num = CountCheckouts(i) if num > 0: msg = "This project has %d items checked out\r\n\r\nDo you still want to continue?" % num import win32ui if win32ui.MessageBox(msg, project, win32con.MB_YESNO) != win32con.IDYES: return oldBuild = buildNo = GetLastBuildNo(project) if buildNo is None: buildNo = "1" oldBuild = "<None>" else: try: buildNo = string.atoi(buildNo) if not bRebrand: buildNo = buildNo + 1 buildNo = str(buildNo) except ValueError: raise error("The previous label could not be incremented: %s" % (oldBuild)) if not auto: from pywin.mfc import dialog buildNo = dialog.GetSimpleInput("Enter new build number", buildNo, "%s - Prev: %s" % (project, oldBuild)) if buildNo is None: return i.Label(buildNo, "Build %s: %s" % (buildNo, buildDesc)) if auto: print("Branded project %s with label %s" % (project, buildNo)) return buildNo
def ReloadAllControls(btnProcessor,*args): server = NewConn.getitem('_server') port = NewConn.getitem('_port') btnProcessor.window.LoadAllControls() if str(NewConn.getitem('_running')) == 'False': win32ui.MessageBox("No server running on host "+ server+" at port "+str(port), "Server Connection", flag_excl) return
def OnAdd(self, msg, code): doc, view = scriptutils.GetActiveEditorDocument() if doc is None: ## Don't do a messagebox, as this could be triggered from the app's ## idle loop whenever the debug toolbar is visible, giving a never-ending ## series of dialogs. This can happen when the OnUpdate handler ## for the toolbar button IDC_DBG_ADD fails, since MFC falls back to ## sending a normal command if the UI update command fails. ## win32ui.MessageBox('There is no active window - no breakpoint can be added') warnings.warn( 'There is no active window - no breakpoint can be added') return None pathName = doc.GetPathName() lineNo = view.LineFromChar(view.GetSel()[0]) + 1 # If I have a debugger, then tell it, otherwise just add a marker d = self._GetDebugger() if d is None: import pywin.framework.editor.color.coloreditor doc.MarkerToggle( lineNo, pywin.framework.editor.color.coloreditor.MARKER_BREAKPOINT) else: if d.get_break(pathName, lineNo): win32ui.SetStatusText('Clearing breakpoint', 1) rc = d.clear_break(pathName, lineNo) else: win32ui.SetStatusText('Setting breakpoint', 1) rc = d.set_break(pathName, lineNo) if rc: win32ui.MessageBox(rc) d.GUIRespondDebuggerData()
def msgbox(): '''用户选择查询条件,点击弹框的确定或取消按钮,获得返回值''' returnvalue=win32ui.MessageBox('请选择查询条件','选择条件框',1) if returnvalue==1: '''点击查询按钮''' self.chaxun_weianliuzhuan() sleep(2) else: pass sleep(1) '''获得要用户要分配的案件数量''' anjian_num=create_frame() print('最终返回值为'+str(anjian_num)) if anjian_num>100: num_int=anjian_num//100 #取整数 num_mod=anjian_num%100 #取余数 elif anjian_num>50: num_int = anjian_num // 50 # 取整数 num_mod = anjian_num % 50 # 取余数 elif anjian_num>10: num_int = anjian_num // 10 # 取整数 num_mod = anjian_num % 10 # 取余数 elif anjian_num>0: pass else: print('输入有误,请重新输入')