def _directory(): try: pidl, display_name, image_list = shell.SHBrowseForFolder() return shell.SHGetPathFromIDList(pidl) except TypeError, e: if e.message == "None is not a valid ITEMIDLIST in this context": return []
def GetFolder(message=None): """ Select folder dialog. Returns path if one is selected. Otherwise it returns None. Availability: FontLab, Macintosh, PC """ path = None if MAC: if haveMacfs: fss, ok = macfs.GetDirectory(message) if ok: path = fss.as_pathname() else: from robofab.interface.mac.getFileOrFolder import GetFileOrFolder # This _also_ allows the user to select _files_, but given the # package/folder dichotomy, I think we have no other choice. path = GetFileOrFolder(message) elif PC: if inFontLab: if not message: message = '' path = fl.GetPathName('', message) else: myTuple = shell.SHBrowseForFolder(0, None, message, 64) try: path = shell.SHGetPathFromIDList(myTuple[0]) except: pass else: _raisePlatformError('GetFile') return path
def askForApacheDir(apachediroptions): # try to ask for Apache directory if len(apachediroptions) > 0: # get the most recent version... versionnames = apachediroptions.keys() versionnames.sort() initialdir = apachediroptions[versionnames[-1]] else: initialdir = "C:/Program Files/Apache Group/Apache2" # TODO: let the user select the name from a list, or click browse to choose... try: from tkFileDialog import askdirectory from Tkinter import Tk root = Tk() root.withdraw() path = askdirectory(title="Where is Apache installed?", initialdir=initialdir, mustexist=1, master=root) root.quit() root.destroy() return path except ImportError: try: from win32com.shell import shell pidl, displayname, imagelist = shell.SHBrowseForFolder( 0, None, "Where is Apache installed?") path = shell.SHGetPathFromIDList(pidl) return path except ImportError: return ""
def browse_folder(_, title): """Ask the user to select a folder. Return full path.""" pidl = shell.SHBrowseForFolder(None, None, title)[0] if pidl is None: # user cancelled return None fullpath = shell.SHGetPathFromIDList(pidl) return fullpath
def choose_folder(title=strings.choose_folder): desktop_pidl = shell.SHGetFolderLocation(0, shellcon.CSIDL_DESKTOP, 0, 0) pidl, display_name, image_list = shell.SHBrowseForFolder( win32gui.GetDesktopWindow(), desktop_pidl, title, 0, None, None) if pidl: path = shell.SHGetPathFromIDListW(pidl) set_last_cwd(path) return path
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 browse_folder(_, title): """Ask the user to select a folder. Return full path.""" flags = 0x0010 #SHBrowseForFolder path input pidl = shell.SHBrowseForFolder(None, None, title, flags)[0] if pidl is None: # user cancelled return None fullpath = shell.SHGetPathFromIDListW(pidl) return fullpath
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 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 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 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 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 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 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 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 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 _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 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 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 _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_fn(msg=u'Выберите файл'): # root root = None from win32com.shell import shell # import os flag = 0xFFFF # Флаги полноты объектов выбора # Сейчас подняты все (методом тыка) надо найти описание try: pidl = shell.SHBrowseForFolder(0, root, msg, flag) except: print(u'Ошибка выбора файла') return None path = shell.SHGetPathFromIDList(pidl[0]) return path #print "%s" %get_fn()
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 if __name__ == '__main__': # Demonstrate a dialog with the cwd selected as the default - this # must be done via a callback function. flags = shellcon.BIF_STATUSTEXT shell.SHBrowseForFolder( 0, # parent HWND None, # root PIDL. "Default of %s" % os.getcwd(), # title flags, # flags BrowseCallbackProc, # callback function os.getcwd() # 'data' param for the callback ) # Browse from this directory down only. # Get the PIDL for the cwd. desktop = shell.SHGetDesktopFolder() cb, pidl, extra = desktop.ParseDisplayName(0, None, os.getcwd()) shell.SHBrowseForFolder( 0, # parent HWND pidl, # root PIDL. "From %s down only" % os.getcwd(), # title )
def main(): #delete any leftover previously created delivery notes folders leftover_del_notes_folders = glob.glob('\Delivery Notes*') for folder in leftover_del_notes_folders: shutil.rmtree(folder) #open browser window to enable user to choose file to create delivery #notes from desktop_pidl = shell.SHGetFolderLocation(0, shellcon.CSIDL_DESKTOP, 0, 0) pidl, display_name, image_list = shell.SHBrowseForFolder( win32gui.GetDesktopWindow(), desktop_pidl, "Please select the file you would \ like to create your delivery notes from.", shellcon.BIF_BROWSEINCLUDEFILES, None, None) if (pidl, display_name, image_list) == (None, None, None): print vis_demarc_line + "\n\n\tNothing selected" else: fin = shell.SHGetPathFromIDList(pidl) #open Excel workbook workbook_in = xlrd.open_workbook(fin) #Iterate through worksheets print vis_demarc_line + "\n\n\t" for sheet in workbook_in.sheets(): store = sheet.name worksheet = workbook_in.sheet_by_name(store) #Grab data from input workbook store_name = worksheet.cell(0, 1) store_address_cell = sheet.cell(1, 1) store_code = worksheet.cell(3, 1) store_address = re.split("[,.]", store_address_cell.value) #Create dictionary to store address address_dict = {} #Load address into dictionary i = 1 for address_line in store_address: address_dict[i] = address_line i += 1 #Define devices in each worksheet, where all_devices is a #list of devices switch_col = worksheet.col_values(4, 6, 15) ap_col = worksheet.col_values(1, 17, 36) list_of_switches = list(set(switch_col)) list_of_switches.remove('') list_of_aps = list(set(ap_col)) all_devices = list_of_switches + list_of_aps #Save sheet as temporary csv file for easier data collection with open(store + '-temp.csv', 'w') as csv_in: csv_temp = csv.writer(csv_in) for row in range(worksheet.nrows): csv_temp.writerow(worksheet.row_values(row)) #Parse csv file for device and serial data device1 = all_devices[0] device2 = all_devices[1] device3 = None if len(all_devices) > 3: device3 = all_devices[2] device4 = all_devices[-1] #Create empty device lists, where the name of each list is a #different device model device1_list = [] device2_list = [] device3_list = [] device4_list = [] #Build device lists with device serial numbers with open(store + '-temp.csv', 'r') as csv_out: lines = csv_out.readlines() for line in lines: if device1 in line and \ (line.split(',')[-2] != ''): device1_list.append(line.split(',')[-2]) elif device2 in line and \ (line.split(',')[-2] != ''): device2_list.append(line.split(',')[-2]) elif (len(all_devices) > 3) and \ device3 in line and \ (line.split(',')[-2] != ''): device3_list.append(line.split(',')[-2]) elif device4 in line and \ (line.split(',')[2] != ''): device4_list.append(line.split(',')[2]) #Show progress to user print '\n\tCreating %s (%s) delivery note...\n' % (store_name.value, store_code.value) #Create delivery note workbook workbook_out = Workbook() del_note = workbook_out.add_sheet('Delivery Note', cell_overwrite_ok=True) #Format delivery note workbook format_delivery_note(del_note) #Write store name and address to delivery note store_code_statement = 'Store code: %s' % store_code.value del_note.write_merge(10, 10, 0, 3, store_name.value, left_and_right_border_left_align) del_note.write_merge(11, 11, 0, 3, address_dict.get(1), left_and_right_border_left_align) del_note.write_merge(12, 12, 0, 3, address_dict.get(2), left_and_right_border_left_align) del_note.write_merge(13, 13, 0, 3, address_dict.get(3), left_and_right_border_left_align) del_note.write_merge(14, 14, 0, 3, address_dict.get(4), left_and_right_border_left_align) del_note.write_merge(15, 15, 0, 3, address_dict.get(5), left_and_right_border_left_align) del_note.write_merge(16, 16, 0, 3, address_dict.get(6), left_and_right_border_left_align) del_note.write_merge(17, 17, 0, 3, store_code_statement, all_borders_centre_align) #Specify device quantities i = 20 j = i + len(device1_list) k = j + len(device2_list) l = k + len(device3_list) total_no_of_devices = (len(device1_list) + len(device2_list) + len(device3_list) + len(device4_list)) #write device model names to delivery note del_note.write_merge(i, i, 2, 5, device1, all_borders_centre_align) del_note.write_merge(j, j, 2, 5, device2, all_borders_centre_align) del_note.write_merge(k, k, 2, 5, device3, all_borders_centre_align) del_note.write_merge(l, l, 2, 5, device4, all_borders_centre_align) #Write device quantities to delivery note del_note.write_merge(i, i, 0, 1, len(device1_list), all_borders_centre_align) del_note.write_merge(j, j, 0, 1, len(device2_list), all_borders_centre_align) del_note.write_merge(k, k, 0, 1, len(device3_list), all_borders_centre_align) del_note.write_merge(l, l, 0, 1, len(device4_list), all_borders_centre_align) #Write device lists to excel file for item in device1_list: del_note.write_merge(i, i, 6, 9, item, all_borders_centre_align) i += 1 for item in device2_list: del_note.write_merge(j, j, 6, 9, item, all_borders_centre_align) j += 1 for item in device3_list: del_note.write_merge(k, k, 6, 9, item, all_borders_centre_align) k += 1 for item in device4_list: del_note.write_merge(l, l, 6, 9, item, all_borders_centre_align) l += 1 #Write number of boxes to delivery note total_boxes = '%d BOXES IN TOTAL' % total_no_of_devices row1 = total_no_of_devices + 20 row2 = row1 + 1 del_note.write_merge(row1, row2, 0, 9, total_boxes, all_borders_centre_align) #Delete temp csv files os.remove(store + '-temp.csv') #create 'Delivery Notes' folder within the same directory as the #Excel spreadsheet if it doesn't already exist folder_timestr = time.strftime("%d%m%Y") del_notes_dir = desktop_path + '\Delivery Notes-' + folder_timestr + '\\' if not os.path.exists(del_notes_dir): os.makedirs(del_notes_dir) #Save excel file workbook_out.save(del_notes_dir + store_code.value + '-' + total_boxes + '.xls') print( vis_demarc_line + "\n\n\tYour delivery notes have been created here:\n\n\t%s" % del_notes_dir + vis_demarc_line + '\n\n')
def __init__ (self, host, port, vmrun, vmx, snap_name=None, log_level=1, interactive=False): ''' @type host: String @param host: Hostname or IP address to bind server to @type port: Integer @param port: Port to bind server to @type vmrun: String @param vmrun: Path to VMWare vmrun.exe @type vmx: String @param vmx: Path to VMX file @type snap_name: String @param snap_name: (Optional, def=None) Snapshot name to revert to on restart @type log_level: Integer @param log_level: (Optional, def=1) Log output level, increase for more verbosity @type interactive: Boolean @param interactive: (Option, def=False) Interactive mode, prompts for input values ''' # initialize the PED-RPC server. pedrpc.server.__init__(self, host, port) self.host = host self.port = port self.interactive = interactive if interactive: print "[*] Entering interactive mode..." # get vmrun path try: while 1: print "[*] Please browse to the folder containing vmrun.exe..." pidl, disp, imglist = shell.SHBrowseForFolder(0, None, "Please browse to the folder containing vmrun.exe:") fullpath = shell.SHGetPathFromIDList(pidl) file_list = os.listdir(fullpath) if "vmrun.exe" not in file_list: print "[!] vmrun.exe not found in selected folder, please try again" else: vmrun = fullpath + "\\vmrun.exe" print "[*] Using %s" % vmrun break except: print "[!] Error while trying to find vmrun.exe. Try again without -I." sys.exit(1) # get vmx path try: while 1: print "[*] Please browse to the folder containing the .vmx file..." pidl, disp, imglist = shell.SHBrowseForFolder(0, None, "Please browse to the folder containing the .vmx file:") fullpath = shell.SHGetPathFromIDList(pidl) file_list = os.listdir(fullpath) exists = False for file in file_list: idx = file.find(".vmx") if idx == len(file) - 4: exists = True vmx = fullpath + "\\" + file print "[*] Using %s" % vmx if exists: break else: print "[!] No .vmx file found in the selected folder, please try again" except: raise print "[!] Error while trying to find the .vmx file. Try again without -I." sys.exit(1) # Grab snapshot name and log level if we're in interactive mode if interactive: snap_name = raw_input("[*] Please enter the snapshot name: ") log_level = raw_input("[*] Please enter the log level (default 1): ") if log_level: log_level = int(log_level) else: log_level = 1 # if we're on windows, get the DOS path names if os.name == "nt": self.vmrun = GetShortPathName(r"%s" % vmrun) self.vmx = GetShortPathName(r"%s" % vmx) else: self.vmrun = vmrun self.vmx = vmx self.snap_name = snap_name self.log_level = log_level self.interactive = interactive self.log("VMControl PED-RPC server initialized:") self.log("\t vmrun: %s" % self.vmrun) self.log("\t vmx: %s" % self.vmx) self.log("\t snap name: %s" % self.snap_name) self.log("\t log level: %d" % self.log_level) self.log("Awaiting requests...")
# # dlg = win32ui.CreateFileDialog(0) # dlg.SetOFNInitialDir("C:") # flag = dlg.DoModal() # print(flag) # if 1 == flag: # print(dlg.GetPathName()) # else: # print("取消另存为...") 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) # import os # import win32gui # from win32com.shell import shell, shellcon # # mydocs_pidl = shell.SHGetFolderLocation (0, shellcon.CSIDL_PERSONAL, 0, 0) # pidl, display_name, image_list = shell.SHBrowseForFolder ( # win32gui.GetDesktopWindow (), # mydocs_pidl, # "Select a file or folder", # shellcon.BIF_BROWSEINCLUDEFILES,
def __init__(self, host, port, vmrun, vmx, snap_name=None, log_level=1, interactive=False): """ Controls an Oracle VirtualBox Virtual Machine @type host: str @param host: Hostname or IP address to bind server to @type port: int @param port: Port to bind server to @type vmrun: str @param vmrun: Path to VBoxManage @type vmx: str @param vmx: Name of the virtualbox VM to control (no quotes) @type snap_name: str @param snap_name: (Optional, def=None) Snapshot name to revert to on restart @type log_level: int @param log_level: (Optional, def=1) Log output level, increase for more verbosity @type interactive: bool @param interactive: (Option, def=False) Interactive mode, prompts for input values """ # initialize the PED-RPC server. pedrpc.Server.__init__(self, host, port) self.host = host self.port = port self.interactive = interactive if interactive: print "[*] Entering interactive mode..." # get vmrun path try: while 1: print "[*] Please browse to the folder containing VBoxManage.exe..." pidl, disp, imglist = shell.SHBrowseForFolder( 0, None, "Please browse to the folder containing VBoxManage.exe" ) fullpath = shell.SHGetPathFromIDList(pidl) file_list = os.listdir(fullpath) if "VBoxManage.exe" not in file_list: print "[!] VBoxManage.exe not found in selected folder, please try again" else: vmrun = fullpath + "\\VBoxManage.exe" print "[*] Using %s" % vmrun break except Exception: print "[!] Error while trying to find VBoxManage.exe. Try again without -I." sys.exit(1) # Grab vmx, snapshot name and log level if we're in interactive mode if interactive: vmx = raw_input( "[*] Please enter the VirtualBox virtual machine name: ") snap_name = raw_input("[*] Please enter the snapshot name: ") log_level = raw_input( "[*] Please enter the log level (default 1): ") if log_level: log_level = int(log_level) else: log_level = 1 # if we're on windows, get the DOS path names if os.name == "nt": self.vmrun = GetShortPathName(r"%s" % vmrun) self.vmx = GetShortPathName(r"%s" % vmx) else: self.vmrun = vmrun self.vmx = vmx self.snap_name = snap_name self.log_level = log_level self.interactive = interactive self.log("VirtualBox PED-RPC server initialized:") self.log("\t vboxmanage: %s" % self.vmrun) self.log("\t machine name: %s" % self.vmx) self.log("\t snap name: %s" % self.snap_name) self.log("\t log level: %d" % self.log_level) self.log("Awaiting requests...")
def get_dir_path(): from win32com.shell import shell file_info = shell.SHBrowseForFolder() if file_info[0] is None: raise ValueError("目标文件夹不存在或者存在其他错误") return shell.SHGetPathFromIDList(file_info[0]).decode()