def run(self): try: if mode != "dir": args = {} if self.path: atgs["InitialDir"] = os.path.dirname(self.path) args["File"] = os.path.splitext(os.path.dirname( self.path))[0] args["DefExt"] = os.path.splitext( os.path.dirname(self.path))[1] args["Title"] = self.title if self.title else "Pick a file..." args["CustomFilter"] = 'Other file types\x00*.*\x00' args["FilterIndex"] = 1 filters = "" for f in self.filters: if type(f) == str: filters += (f + "\x00") * 2 else: filters += f[0] + "\x00" + ";".join(f[1:]) + "\x00" args["Filter"] = filters flags = win32con.OFN_EXTENSIONDIFFERENT | win32con.OFN_OVERWRITEPROMPT if self.multiple: flags |= win32con.OFN_ALLOWmultiple | win32con.OFN_EXPLORER if self.show_hidden: flags |= win32con.OFN_FORCESHOWHIDDEN args["Flags"] = flags if self.mode == "open": self.fname, self.customfilter, self.flags = win32gui.GetOpenFileNameW( **args) elif self.mode == "save": self.fname, self.customfilter, self.flags = win32gui.GetSaveFileNameW( **args) if self.fname: if self.multiple: seq = str(self.fname).split("\x00") dir_n, base_n = seq[0], seq[1:] self.selection = [ os.path.join(dir_n, i) for i in base_n ] else: self.selection = str(self.fname).split("\x00") else: # From http://timgolden.me.uk/python/win32_how_do_i/browse-for-a-folder.html pidl, display_name, image_list = shell.SHBrowseForFolder( win32gui.GetDesktopWindow(), None, self.title if self.title else "Pick a folder...", 0, None, None) self.selection = [str(shell.SHGetPathFromIDList(pidl))] return self.selection except (RuntimeError, pywintypes.error): return None
def browse_folder(hwnd, title): """Ask the user to select a folder. Return full path.""" #사용자가 폴더를 선택하면 전체 경로를 반환하고 아니면 none을 반환한다. pidl = shell.SHBrowseForFolder(hwnd, None, title)[0] if pidl is None: # user cancelled return None fullpath = shell.SHGetPathFromIDList(pidl) return fullpath
def gui_select_dir(self, start_dir=None): from win32com.shell import shell try: pidl, _, _ = shell.SHBrowseForFolder() fname = shell.SHGetPathFromIDList(pidl) except Exception, e: print "Failed to get directory: %s" % e return None
def ExplorePIDL(): pidl = shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_DESKTOP) print("The desktop is at", shell.SHGetPathFromIDList(pidl)) shell.ShellExecuteEx(fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, nShow=win32con.SW_NORMAL, lpClass="folder", lpVerb="explore", lpIDList=pidl) print("Done!")
def get_save_path(): # 获取保存的文件夹 import win32gui from win32com.shell import shell, shellcon desktop_pidl = shell.SHGetFolderLocation(0, shellcon.CSIDL_DESKTOP, 0, 0) pidl, display_name, image_list = shell.SHBrowseForFolder( win32gui.GetDesktopWindow(), desktop_pidl, "Choose a folder", 0, None, None) # 获取 print(shell.SHGetPathFromIDList(pidl)) l = shell.SHGetPathFromIDList(pidl) print(l) return l # 获得输入的文件名 # return filename pass
def gui_select_dir(self, start_dir=None): # pylint: disable-msg=W0703,W0613 from win32com.shell import shell try: pidl, _, _ = shell.SHBrowseForFolder() fname = shell.SHGetPathFromIDList(pidl) except Exception, e: print("dPlatform :ailed to get directory: %s" % e) return None
def selectdir_win(initialdir): title = 'Select directory' pidl = shell.SHILCreateFromPath(initialdir, 0)[0] pidl, display_name, image_list = shell.SHBrowseForFolder(None, pidl, title, 0, None, None) if (pidl, display_name, image_list) == (None, None, None): return None else: path = shell.SHGetPathFromIDList(pidl) return path
def askOpenFolderWin32(title, initialDir): try: desktop_pidl = shell.SHGetFolderLocation(0, shellcon.CSIDL_DESKTOP, 0, 0) pidl, display_name, image_list = shell.SHBrowseForFolder( win32gui.GetDesktopWindow(), desktop_pidl, "Choose a folder", 0, None, None) return shell.SHGetPathFromIDList(pidl) except pywintypes.com_error as e: if e.args[0] == -2147467259: print "Invalid folder selected"
def createDesktopLnk(filename,lnkname): shortcut = pythoncom.CoCreateInstance( shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) shortcut.SetPath(filename) if os.path.splitext(lnkname)[-1] != '.lnk': lnkname += ".lnk" # get desktop path desktopPath = shell.SHGetPathFromIDList(shell.SHGetSpecialFolderLocation(0,shellcon.CSIDL_DESKTOP)) lnkname = os.path.join(desktopPath,lnkname) shortcut.QueryInterface(pythoncom.IID_IPersistFile).Save(lnkname,0)
def user_rcpath_win32(): '''return os-specific hgrc search path to the user dir''' userdir = os.path.expanduser('~') if sys.getwindowsversion()[3] != 2 and userdir == '~': # We are on win < nt: fetch the APPDATA directory location and use # the parent directory as the user home dir. appdir = shell.SHGetPathFromIDList( shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_APPDATA)) userdir = os.path.dirname(appdir) return [os.path.join(userdir, 'mercurial.ini'), os.path.join(userdir, '.hgrc')]
def getDefaultDocumentsDirectory(): if sys.platform == 'win32': try: from win32com.shell import shell df = shell.SHGetDesktopFolder() pidl = df.ParseDisplayName(0, None, "::{450d8fba-ad25-11d0-98a8-0800361b1103}")[1] return shell.SHGetPathFromIDList(pidl) except: print "L'extension win32com pour python est recommandée (plateforme windows) !" return os.getcwd() else: return os.getcwd()
def BrowseCallbackProc(hwnd, msg, lp, data): if msg == shellcon.BFFM_INITIALIZED: win32gui.SendMessage(hwnd, shellcon.BFFM_SETSELECTION, 1, data) elif msg == shellcon.BFFM_SELCHANGED: # Set the status text of the # For this message, 'lp' is the address of the PIDL. pidl = shell.AddressAsPIDL(lp) try: path = shell.SHGetPathFromIDList(pidl) win32gui.SendMessage(hwnd, shellcon.BFFM_SETSTATUSTEXT, 0, path) except shell.error: # No path for this PIDL pass
def OnIconButton(self, evt): try: if sys.platform == 'win32': # Arno goes win32, find location of "My Pictures" # see http://www.mvps.org/access/api/api0054.htm from win32com.shell import shell pidl = shell.SHGetSpecialFolderLocation(0, 0x27) path = shell.SHGetPathFromIDList(pidl) else: path = os.path.expandvars('$HOME') except Exception, msg: path = '' print_exc()
def get_documents_dir(): """:returns: the documents dir for the current user""" if _system == 'Linux': return _get_xdg_dir("XDG_DOCUMENTS_DIR", "~/Documents") elif _system == 'Windows': from win32com.shell import shell MY_DOCUMENTS = "::{450d8fba-ad25-11d0-98a8-0800361b1103}" folder = shell.SHGetDesktopFolder() pidl = folder.ParseDisplayName(0, None, MY_DOCUMENTS)[1] return shell.SHGetPathFromIDList(pidl) elif _system == 'Darwin': return os.path.join(os.environ['HOME'], 'Documents') else: raise SystemExit("unknown system: %s" % (_system, ))
def create_file_dialog(self, dialog_type, directory, allow_multiple, save_filename): if not directory: directory = os.environ['temp'] try: if dialog_type == FOLDER_DIALOG: desktop_pidl = shell.SHGetFolderLocation( 0, shellcon.CSIDL_DESKTOP, 0, 0) pidl, display_name, image_list =\ shell.SHBrowseForFolder(self.hwnd, desktop_pidl, None, 0, None, None) file_path = (shell.SHGetPathFromIDList(pidl).decode("utf-8"), ) elif dialog_type == OPEN_DIALOG: file_filter = localization[ "windows.fileFilter.allFiles"] + u"\0*.*\0" custom_filter = localization[ "windows.fileFilter.otherFiles"] + u"\0*.*\0" flags = win32con.OFN_EXPLORER if allow_multiple: flags = flags | win32con.OFN_ALLOWMULTISELECT file_path, customfilter, flags = \ win32gui.GetOpenFileNameW(self.hwnd, InitialDir=directory, Flags=flags, File=None, DefExt="", Title="", Filter=file_filter, CustomFilter=custom_filter, FilterIndex=0) parts = file_path.split('\x00') if len(parts) > 1: file_path = tuple([ os.path.join(parts[0], file_name) for file_name in parts[1:] ]) else: file_path = (file_path, ) elif dialog_type == SAVE_DIALOG: file_filter = localization[ "windows.fileFilter.allFiles"] + u"\0*.*\0" custom_filter = localization[ "windows.fileFilter.otherFiles"] + u"\0*.*\0" file_path, customfilter, flags = \ win32gui.GetSaveFileNameW(self.hwnd, InitialDir=directory, File=save_filename, DefExt="", Title="", Filter=file_filter, CustomFilter=custom_filter, FilterIndex=0) except Exception as e: logger.debug("File dialog crash", exc_info=True) file_path = None return file_path
def get_my_documents(): """Return the My Docuemnts folder""" df = shell.SHGetDesktopFolder() pidl = df.ParseDisplayName(0, None, "::{450d8fba-ad25-11d0-98a8-0800361b1103}")[1] mydocs = shell.SHGetPathFromIDList(pidl) # TODO: may need to handle window-specific encoding here. #encoding = locale.getdefaultlocale()[1] #if encoding is None: # encoding = "utf-8" return mydocs
def _setup_file_handler(): global _file_handler # import traceback; traceback.print_stack() if not _file_handler: # Lookup path the user's personal folder in which # to log Dragonfly messages. mydocs_pidl = shell.SHGetFolderLocation(0, shellcon.CSIDL_PERSONAL, 0, 0) mydocs_path = shell.SHGetPathFromIDList(mydocs_pidl) log_file_path = os.path.join(mydocs_path, "dragonfly.txt") _file_handler = logging.FileHandler(log_file_path) formatter = logging.Formatter("%(asctime)s %(name)s (%(levelname)s):" " %(message)s" + repr(_file_handler)) _file_handler.setFormatter(formatter) return _file_handler
def GetImagePath(btnProcessor,*args): from win32com.shell import shell, shellcon ulFlags = shellcon.BIF_BROWSEINCLUDEFILES | BIF_NEWDIALOGSTYLE | BIF_NONEWFOLDERBUTTON pidl, display_name, image_list=shell.SHBrowseForFolder(btnProcessor.window.hwnd, # parent HWND None, # root PIDL. "Get the image path", # title ulFlags, # flags BrowseCallbackProc, # callback function os.getcwd() # 'data' param for the callback ) if (pidl, display_name, image_list) == (None, None, None): return else: path = shell.SHGetPathFromIDList (pidl) win32gui.SetDlgItemText(btnProcessor.window.hwnd, btnProcessor.other_ids[0], path)
def chooseOpenFolder(): """ Open a dialog for user to choose a folder/directory. :return: the path to the folder, or None if not selected. """ pidl, display_name, image_list = shell.SHBrowseForFolder( win32gui.GetDesktopWindow(), desktop_pidl, "Choose a folder", 0, None, None) if pidl is None: return None return shell.SHGetPathFromIDList(pidl)
def create_file_dialog(self, dialog_type, directory, allow_multiple, save_filename): if not directory: directory = os.environ['temp'] try: if dialog_type == FOLDER_DIALOG: desktop_pidl = shell.SHGetFolderLocation( 0, shellcon.CSIDL_DESKTOP, 0, 0) pidl, display_name, image_list =\ shell.SHBrowseForFolder(self.hwnd, desktop_pidl, None, 0, None, None) file_path = (shell.SHGetPathFromIDList(pidl), ) elif dialog_type == OPEN_DIALOG: file_filter = 'All Files\0*.*\0' custom_filter = 'Other file types\0*.*\0' flags = win32con.OFN_EXPLORER if allow_multiple: flags = flags | win32con.OFN_ALLOWMULTISELECT file_path, customfilter, flags = \ win32gui.GetOpenFileNameW(InitialDir=directory, Flags=flags, File=None, DefExt='', Title='', Filter=file_filter, CustomFilter=custom_filter, FilterIndex=0) parts = file_path.split('\x00') if len(parts) > 1: file_path = tuple([ os.path.join(parts[0], file_name) for file_name in parts[1:] ]) else: file_path = (file_path, ) elif dialog_type == SAVE_DIALOG: file_filter = 'All Files\0*.*\0' custom_filter = 'Other file types\0*.*\0' file_path, customfilter, flags = \ win32gui.GetSaveFileNameW(InitialDir=directory, File=save_filename, DefExt='', Title='', Filter=file_filter, CustomFilter=custom_filter, FilterIndex=0) parts = file_path.split('\x00') return file_path except: return None
def getUserDocumentsPath(): """ Find the user's "Documents" directory (OS X), "My Documents" directory (Windows), or home directory (Unix). """ # OS X and Windows code from: # http://www.blueskyonmars.com/2005/08/05 # /finding-a-users-my-documents-folder-on-windows/ # Alternate Windows code from: # http://bugs.python.org/issue1763 if sys.platform.startswith('win'): if sys.platform.startswith('win32'): # Try the primary method on 32-bit windows try: from win32com.shell import shell alt = False except ImportError: try: import ctypes dll = ctypes.windll.shell32 alt = True except: raise Exception("Could not find 'My Documents'") else: # Use the alternate method on 64-bit Windows alt = True if not alt: # Primary method using win32com df = shell.SHGetDesktopFolder() pidl = df.ParseDisplayName(0, None, "::{450d8fba-ad25-11d0-98a8-0800361b1103}")[1] path = shell.SHGetPathFromIDList(pidl) else: # Alternate method using ctypes rather than win32com buf = ctypes.create_string_buffer(300) dll.SHGetSpecialFolderPathA(None, buf, 0x0005, False) path = buf.value elif sys.platform.startswith('darwin'): from Carbon import Folder, Folders folderref = Folder.FSFindFolder(Folders.kUserDomain, Folders.kDocumentsFolderType, False) path = folderref.as_pathname() else: path = os.getenv('HOME') return path
def _request_old_dir(prompt, default_dir): from win32com.shell import shell as sh import win32com.shell.shellcon as sc win_bif_flags = sc.BIF_RETURNONLYFSDIRS # | sc.BIF_EDITBOX | wc.BIF_VALIDATE if default_dir: def callback(hwnd, msg, lp, data): if msg == sc.BFFM_INITIALIZED: api.SendMessage(hwnd, sc.BFFM_SETSELECTION, True, default_dir.path) else: callback = None (idl, name, images) = sh.SHBrowseForFolder(None, None, win_fix_prompt(prompt), win_bif_flags, callback) if idl: return DirRef(sh.SHGetPathFromIDList(idl))
def exposed_select_directory(self): if self._pytis_on_windows(): import win32gui from win32com.shell import shell, shellcon # Get PIDL of the topmost folder for the dialog desktop_pidl = shell.SHGetFolderLocation(0, shellcon.CSIDL_DESKTOP, 0, 0) pidl, display_name, image_list = shell.SHBrowseForFolder( win32gui.GetDesktopWindow(), desktop_pidl, u"Výběr adresáře", 0, None, None) # Transform PIDL back to a directory name and return it return shell.SHGetPathFromIDList(pidl) else: import PyZenity as zenity directory_list = zenity.GetDirectory() if directory_list and len(directory_list) > 0: return directory_list[0] else: return None
def user_rcpath(): path = [] try: home = os.path.expanduser('~') if sys.getwindowsversion()[3] != 2 and home == '~': # We are on win < nt: fetch the APPDATA directory location and use # the parent directory as the user home dir. appdir = shell.SHGetPathFromIDList( shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_APPDATA)) home = os.path.dirname(appdir) path.append(os.path.join(home, '.couchapp.conf')) except: home = os.path.expanduser('~') path.append(os.path.join(home, '.couchapp.conf')) userprofile = os.environ.get('USERPROFILE') if userprofile: path.append(os.path.join(userprofile, '.couchapp.conf')) return path
def get_desktop_path2(): ''' 返回桌面全路径,末尾不带\ ''' from win32com.shell import shell from win32com.shell import shellcon result = None try: from win32com.shell import shell from win32com.shell import shellcon desktop_path = shell.SHGetPathFromIDList( shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_DESKTOP)) result = desktop_path.decode() except: print(traceback.format_exc()) result = None return result
def selecdirectori(): mydocs_pidl = shell.SHGetFolderLocation (0, shellcon.CSIDL_DESKTOP, 0, 0) pidl, display_name, image_list = shell.SHBrowseForFolder ( win32gui.GetDesktopWindow (), mydocs_pidl, "Select a file or folder", shellcon.BIF_BROWSEINCLUDEFILES, None, None ) if (pidl, display_name, image_list) == (None, None, None): print "Nothing selected" else: path = shell.SHGetPathFromIDList (pidl) #print "Opening", #path a=(path) return a
def openDirDialog(path=""): wnd = win32gui.FindWindow(None, u"文档转转工具") # print wnd if not path: path = "" if not os.path.exists(path): pidl = shell.SHBrowseForFolder(wnd, None, "Plese select Path")[0] else: desktop = shell.SHGetDesktopFolder() cb, pidl, extra = desktop.ParseDisplayName(0, None, path) pidl = shell.SHBrowseForFolder(wnd, None, "Plese select Path")[0] try: selectPath = shell.SHGetPathFromIDList(pidl) except: selectPath = path saveConf({"reportPath": selectPath.decode('gbk')}) return selectPath
def _select_directory(self, title, directory): import win32gui from win32com.shell import shell, shellcon def callback(hwnd, msg, lp, data): if msg == shellcon.BFFM_INITIALIZED: win32gui.SendMessage(hwnd, shellcon.BFFM_SETSELECTION, 1, directory) pidl, dname, imglist = shell.SHBrowseForFolder( win32gui.GetDesktopWindow(), # Get PIDL of the topmost folder for the dialog shell.SHGetFolderLocation(0, shellcon.CSIDL_DESKTOP, 0, 0), title, 0, callback, None, ) # Transform PIDL back to a directory name and return it return shell.SHGetPathFromIDList(pidl)
def path_update(): desktop_pidl = shell.SHGetFolderLocation (0, shellcon.CSIDL_DESKTOP, 0, 0) pidl, display_name, image_list = shell.SHBrowseForFolder ( win32gui.GetDesktopWindow (), desktop_pidl, "Select Steam root folder", 0, None, None ) with open(dir+'\\s_path.sah', 'w') as p: decoded = shell.SHGetPathFromIDList (pidl).decode('utf-8') full_path = decoded + '\\Steam.exe' try: p.write(full_path) except Exception as error: print("An error occured while updating the path: %s" %error) finally: p.close() menu()
def __get_powerpoint_mru(self, str_powerpoint_mru): """Extracts PowerPoint user mru""" # TODO : Win XP self.logger.info("Extracting PowerPoint MRU") hive_list = self._get_list_from_registry_key(registry_obj.HKEY_USERS, str_powerpoint_mru) to_csv_list = [("COMPUTER_NAME", "TYPE", "LAST_WRITE_TIME", "HIVE", "KEY_PATH", "ATTR_NAME", "REG_TYPE", "ATTR_TYPE", "ATTR_DATA")] for item in hive_list: if item[KEY_VALUE_STR] == 'VALUE': if item[VALUE_NAME] != "MRUListEx": pidl = shell.StringAsPIDL(item[VALUE_DATA]) path = shell.SHGetPathFromIDList(pidl) to_csv_list.append((self.computer_name, "PowerPointMRU", item[VALUE_LAST_WRITE_TIME], "HKEY_USERS", item[VALUE_PATH], item[VALUE_NAME], item[KEY_VALUE_STR], registry_obj.get_str_type(item[VALUE_TYPE]), path)) return to_csv_list