def getUserHomeDir(): """Helper method for finding the user home directory. On UNIX systems this is achieved by using the python `os.getenv` module. On Windows NT systems users is able to have roaming or local profiles. For example: - ``CSIDL_APPDATA`` returns the roaming ``Application Data`` dir, - ``CSIDL_LOCAL_APPDATA`` returns the local home dir. Returns the path to the user home directory. """ try: from win32com.shell import shellcon, shell homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0) except ImportError: homedir = os.path.expanduser('~') return homedir
def exportAlbum(self, name, filename): albumService = AlbumService() album = albumService.getAlbum(name) if album is None: return with ZipFile(filename, 'w', ZIP_DEFLATED) as zipFile: musicFolder = shell.SHGetFolderPath(0, shellcon.CSIDL_MYMUSIC, None, 0) for m in album.music: path = os.path.join(musicFolder, m.path) if os.path.isfile(path): zipFile.write(path, m.path) description = self.__createDescriptionForAblum(album) zipFile.writestr(DESCRIPTION_KEY, description)
def set_config(config): """ Switch configuration files to CONFIG. This overwrites the client config file with config.$CONFIG and the server config file with subversion.$CONFIG.conf. """ appdata = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) svn_config_folder = os.path.join(appdata, 'Subversion') svn_config_file = os.path.join(svn_config_folder, 'config') svn_config_template = svn_config_file + '.' + config shutil.copyfile(svn_config_template, svn_config_file) apache_config_folder = os.path.join(apache_path, 'conf', 'extra') apache_config_file = os.path.join(apache_config_folder, 'subversion.conf') apache_config_template = os.path.join(apache_config_folder, 'subversion.' + config + '.conf') shutil.copyfile(apache_config_template, apache_config_file)
def getDocumentsFolder(): if sys.platform == "win32": try: import win32com.client from win32com.shell import shell, shellcon objShell = win32com.client.Dispatch("WScript.Shell") docsFolder = objShell.SpecialFolders("MyDocuments") except Exception, e: print e try: docsFolder = shell.SHGetFolderPath(0, shellcon.CSIDL_MYDOCUMENTS, 0, 0) except Exception: userprofile = os.environ['USERPROFILE'].decode( sys.getfilesystemencoding()) docsFolder = os.path.join(userprofile, "Documents")
def create_desktop_shortcut(): shortcut = pythoncom.CoCreateInstance( shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink, ) # diverge from the straight copypaste to set the working directory shortcut.SetWorkingDirectory(os.path.abspath(os.getcwd())) shortcut.SetPath(os.path.abspath(r".\PyAdSkipper.exe")) shortcut.SetDescription("PyAdSkipper GUI shortcut") shortcut.SetIconLocation(os.path.abspath(r".\icon.ico"), 0) desktop_path = shell.SHGetFolderPath(0, shellcon.CSIDL_DESKTOP, 0, 0) persist_file = shortcut.QueryInterface(pythoncom.IID_IPersistFile) persist_file.Save(os.path.join(desktop_path, "PyAdSkipper.lnk"), 0)
def create_shortcut(folder, name): platform = get_platform() library_folder = Path(get_library_folder()) if platform == 'Windows': targetpath = library_folder / folder / "blender.exe" workingdir = library_folder / folder desktop = shell.SHGetFolderPath(0, shellcon.CSIDL_DESKTOP, None, 0) dist = Path(desktop) / (name + ".lnk") if getattr(sys, 'frozen', False): icon = sys._MEIPASS + "/files/winblender.ico" else: icon = Path( "./resources/icons/winblender.ico").resolve().as_posix() _WSHELL = win32com.client.Dispatch("Wscript.Shell") wscript = _WSHELL.CreateShortCut(dist.as_posix()) wscript.Targetpath = targetpath.as_posix() wscript.WorkingDirectory = workingdir.as_posix() wscript.WindowStyle = 0 wscript.IconLocation = icon wscript.save() elif platform == 'Linux': _exec = library_folder / folder / "blender" icon = library_folder / folder / "blender.svg" desktop = Path.home() / "Desktop" filename = name.replace(' ', '-') dist = desktop / (filename + ".desktop") desktop_entry = \ "[Desktop Entry]\n" + \ "Name={0}\n".format(name) + \ "Comment=3D modeling, animation, rendering and post-production\n" + \ "Keywords=3d;cg;modeling;animation;painting;sculpting;texturing;video editing;video tracking;rendering;render engine;cycles;game engine;python;\n" + \ "Icon={0}\n".format(icon.as_posix().replace(' ', r'\ ')) + \ "Terminal=false\n" + \ "Type=Application\n" + \ "Categories=Graphics;3DGraphics;\n" + \ "MimeType=application/x-blender;\n" + \ "Exec={0} %f".format(_exec.as_posix().replace(' ', r'\ ')) with open(dist, 'w') as file: file.write(desktop_entry)
def get_external_program_location(key): extensions = ["", ".exe"] potential_names = ["%s%s" % (key, ext) for ext in extensions] windows_program_directories = { 'inkscape': ['Inkscape'], 'pstoedit': ['pstoedit'] } # check the windows path via win32api try: import win32api location = win32api.FindExecutable(key)[1] if location: return location except Exception: # Wildcard (non-system exiting) exception to match "ImportError" and # "pywintypes.error" (for "not found"). pass # go through the PATH environment variable if "PATH" in os.environ: path_env = os.environ["PATH"] for one_dir in path_env.split(os.pathsep): for basename in potential_names: location = os.path.join(one_dir, basename) if os.path.isfile(location): return location # do a manual scan in the programs directory (only for windows) program_dirs = ["C:\\Program Files", "C:\\Programme"] try: from win32com.shell import shellcon, shell # The frozen application somehow dows not provide this setting. program_dirs.insert( 0, shell.SHGetFolderPath(0, shellcon.CSIDL_PROGRAM_FILES, 0, 0)) except ImportError: # no other options for non-windows systems pass # scan the program directory for program_dir in program_dirs: for sub_dir in windows_program_directories[key]: for basename in potential_names: location = os.path.join(program_dir, sub_dir, basename) if os.path.isfile(location): return location # nothing found return None
def get_home_dir(): """ Platform-agnostic way to get user home directory """ if sys.platform == "win32": #pragma: no cover # on Windows port try: from win32com.shell import shellcon, shell home_dir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0) # create mdig path if necessary home_dir = os.path.join(home_dir, "mdig") if not os.path.isdir(home_dir): os.mkdir(home_dir) except ImportError: raise ImportError, "The win32com module could not be found" else: # else on POSIX box home_dir = os.path.join(os.path.expanduser("~"), ".mdig") if not os.path.isdir(home_dir): os.mkdir(home_dir) return home_dir
def get_config_dirname(): try: from win32com.shell import shellcon, shell homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0) config_dir = os.path.join(homedir, CONFIG_DIR) except ImportError: # quick semi-nasty fallback for non-windows/win32com case homedir = os.path.expanduser("~") # hide the config directory for unixes config_dir = os.path.join(homedir, "." + CONFIG_DIR) if not os.path.isdir(config_dir): try: os.makedirs(config_dir) except OSError: log.warn( "Failed to create preferences directory in your user's home directory: %s", config_dir) config_dir = None return config_dir
def openexpfile(self): if self.os == 1: docdir = shell.SHGetFolderPath(0, shellcon.CSIDL_PERSONAL, None, 0) elif self.os == 2: docdir = os.getenv("HOME") else: raise EnvironmentError('Unsupported platform') self.initdir = "%s\\Photodetector\\Experiment Files" % docdir self.filename = tkFileDialog.askopenfilename( initialdir=self.initdir, title="Open exp. file", filetypes=(("Text file", ".txt"), ("all files", "*.*"))) #try: self.file = open(self.filename, 'r') self.output = self.file.readlines() self.onports = self.output[1] self.n = int(self.output[3]) self.m = int(self.output[5]) self.parameters = [] self.widgets = [] self.root.destroy() self.main() for exp in range(self.n): line = 2 * exp + 7 llist = self.output[line].split() lllist = [] count = 0 for i in llist: if count >= 1: i = float(i[:-1]) else: i = int(i[1:-1]) lllist.append(i) count += 1 self.parameters.append(lllist) self.widgets[exp].setcolor(self.parameters[exp][0]) self.widgets[exp].setsamples(self.parameters[exp][1]) self.widgets[exp].setamplitude(self.parameters[exp][2]) self.widgets[exp].setoffset(self.parameters[exp][3]) self.widgets[exp].setgain(self.parameters[exp][4])
def get_default_local_folder() -> Path: """ Find a reasonable location for the root Nuxeo Drive folder This folder is user specific, typically under the home folder. Under Windows, try to locate My Documents as a home folder, using the win32com shell API if allowed, else falling back on a manual detection. Note: this function cannot be decorated with lru_cache(). """ if WINDOWS: from win32com.shell import shell, shellcon try: folder = normalized_path( shell.SHGetFolderPath(0, shellcon.CSIDL_PERSONAL, None, 0)) except Exception: """ In some cases (not really sure how this happens) the current user is not allowed to access its 'My Documents' folder path through the win32com shell API, which raises the following error: com_error: (-2147024891, 'Access is denied.', None, None) We noticed that in this case the 'Location' tab is missing in the Properties window of 'My Documents' accessed through the Explorer. So let's fall back on a manual (and poor) detection. WARNING: it's important to check 'Documents' first as under Windows 7 there also exists a 'My Documents' folder invisible in the Explorer and cmd / powershell but visible from Python. First try regular location for documents under Windows 7 and up """ log.warning( "Access denied to the API SHGetFolderPath," " falling back on manual detection", exc_info=True, ) folder = normalized_path(Options.home) / "Documents" else: folder = normalized_path(Options.home) return increment_local_folder(folder, APP_NAME)
def get_prefs_path(): """ full path to our preferences JSON file """ fname = "kiwix-hotspot.prefs" homedir = os.path.expanduser("~") if sys.platform == "win32": try: prefsdir = shell.SHGetFolderPath(0, shellcon.CSIDL_LOCAL_APPDATA, 0, 0) except Exception: prefsdir = homedir elif sys.platform == "linux": prefsdir = os.path.join(homedir, ".config") elif sys.platform == "darwin": prefsdir = os.path.join(homedir, "Library", "Application Support") else: raise NotImplementedError("OS Not Supported") os.makedirs(prefsdir, exist_ok=True) # create folder should it not exist return os.path.join(prefsdir, fname)
def get_homedir(): """return home directory, or best approximation On Windows, this returns the Roaming Profile APPDATA (use CSIDL_LOCAL_APPDATA for Local Profile) """ homedir = '.' if os.name == 'nt': # For Windows, ask for parent of Roaming 'Application Data' directory try: from win32com.shell import shellcon, shell homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0) except ImportError: # if win32com is not found homedir = os.get_environ('HOME', '.') else: try: os.path.expanduser("~") except: pass return homedir
def short_target(filename, dest, arg): import os, sys import pythoncom from win32com.shell import shell, shellcon desktop_path = shell.SHGetFolderPath(0, shellcon.CSIDL_DESKTOP, 0, 0) shortcut_path = os.path.join(desktop_path, filename) if not os.path.exists(shortcut_path): shortcut = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) with open(shortcut_path, 'w'): pass persist_file = shortcut.QueryInterface(pythoncom.IID_IPersistFile) persist_file.Load(shortcut_path) shortcut.SetPath(dest) shortcut.SetArguments(arg) shortcut.SetHotkey(114) persist_file.Save(shortcut_path, 0)
def safely_create_link(link_name, target_path, icon=None): desktop = shell.SHGetFolderPath(0, shellcon.CSIDL_DESKTOP, 0, 0) desktop_files = os.listdir(desktop) for file in desktop_files: if file[-4:] == '.lnk': file_path = os.path.join(desktop, file) file_destination = link_destination(file_path) file_destination_norm = os.path.normcase(os.path.normpath(file_destination)).strip(' /\\') target_path_norm = os.path.normcase(os.path.normpath(target_path)).strip(' /\\') if file_destination_norm == target_path_norm: if icon: link_set_icon(file_path, icon) return if link_name[-4:] != '.lnk': link_name += '.lnk' link_path = os.path.join(desktop, link_name) create_link(link_path, target_path, icon)
def __find_debugger(self, logger, debugger): """Finds the installed debugger""" # We are looking for c:\Program Files (x86)\Windows Kits\8.1\Debuggers\x64 cdb = spawn.find_executable(debugger) if cdb is not None: return cdb from win32com.shell import shell, shellcon # Cygwin via sshd does not expose the normal environment variables # Use the shell api to get the variable instead rootDir = shell.SHGetFolderPath(0, shellcon.CSIDL_PROGRAM_FILESX86, None, 0) for i in range(0, 2): pathToTest = os.path.join(rootDir, "Windows Kits", "8." + str(i), "Debuggers", "x64") logger.info("Checking for debugger in %s" % pathToTest) if(os.path.exists(pathToTest)): return os.path.join(pathToTest, debugger) return None
def tray_on_enso_exec_at_startup(systray, get_state=False): _ = systray startup_dir = shell.SHGetFolderPath(0, shellcon.CSIDL_STARTUP, 0, 0) assert os.path.isdir(startup_dir) link_file = os.path.join(startup_dir, "Enso.lnk") if get_state: return os.path.isfile(link_file) else: if not os.path.isfile(link_file): try: pythoncom.CoInitialize() except: # already initialized. pass shortcut = pythoncom.CoCreateInstance( shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) shortcut.SetPath(ENSO_EXECUTABLE) enso_root_dir = os.path.dirname(ENSO_EXECUTABLE) shortcut.SetWorkingDirectory(enso_root_dir) shortcut.SetIconLocation(os.path.join(enso_root_dir, "Enso.ico"), 0) shortcut.QueryInterface(pythoncom.IID_IPersistFile).Save( link_file, 0) try: pythoncom.CoUnInitialize() except: pass displayMessage( u"<p><command>Enso</command> will be automatically executed at system startup</p><caption>enso</caption>" ) else: os.remove(link_file) displayMessage( u"<p><command>Enso</command> will not start at system startup</p><caption>enso</caption>" )
def get_homedir(): "determine home directory" homedir = None def check(method, s): "check that os.path.expanduser / expandvars gives a useful result" try: if method(s) not in (None, s): return method(s) except: pass return None # for Unixes, allow for sudo case susername = os.environ.get("SUDO_USER", None) if HAS_PWD and susername is not None and homedir is None: homedir = pwd.getpwnam(susername).pw_dir # try expanding '~' -- should work on most Unixes if homedir is None: homedir = check(os.path.expanduser, '~') # try the common environmental variables if homedir is None: for var in ('$HOME', '$HOMEPATH', '$USERPROFILE', '$ALLUSERSPROFILE'): homedir = check(os.path.expandvars, var) if homedir is not None: break # For Windows, ask for parent of Roaming 'Application Data' directory if homedir is None and os.name == 'nt': try: from win32com.shell import shellcon, shell homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0) except ImportError: pass # finally, use current folder if homedir is None: homedir = os.path.abspath('.') return nativepath(homedir)
def get_win_folder_path(csidl, create=False, default=False): """ get the windows current folder path for a csidl useful entries: 'CSIDL_COMMON_DESKTOPDIRECTORY' 'CSIDL_COMMON_STARTMENU' 'CSIDL_COMMON_PROGRAMS' 'CSIDL_PROGRAM_FILES' 'CSIDL_PROGRAM_FILESX86' create when True, will also create it if it does not exists default when True, returns the default directory instead of the current one. """ from win32com.shell import shell, shellcon c = getattr(shellcon, csidl) flag = SHGFP_TYPE_CURRENT if create: c |= CSIDL_FLAG_CREATE if default: flag = SHGFP_TYPE_DEFAULT return shell.SHGetFolderPath(None, c, None, flag)
def getHome(): homedir = os.path.expanduser('~') # ...works on at least windows and linux. # In windows it points to the user's folder # (the one directly under Documents and Settings, not My Documents) # In windows, you can choose to care about local versus roaming profiles. # You can fetch the current user's through PyWin32. # # For example, to ask for the roaming 'Application Data' directory: # (CSIDL_APPDATA asks for the roaming, CSIDL_LOCAL_APPDATA for the local one) # (See microsoft references for further CSIDL constants) try: from win32com.shell import shellcon, shell homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0) except ImportError: # quick semi-nasty fallback for non-windows/win32com case homedir = os.path.expanduser("~") return homedir
def start_browser(self, config, url, options): """ Start browser and load website. """ command = config['command'] if not command: appdata = shell.SHGetFolderPath(0, shellcon.CSIDL_LOCAL_APPDATA, 0, 0) command = appdata + '\Google\Chrome\Application\chrome.exe' print 'running', command try: import subprocess except ImportError: os.spawnl(os.P_DETACH, command, os.path.basename(command), url) else: subprocess.Popen([command, url]) print "Sleeping %d seconds while page is loading." % options.wait time.sleep(options.wait - 10) self.maximize() time.sleep(10)
def __init__(self, searchpaths=[]): self.excl = [ 'Windows', 'Windows.old', 'WINDOWS', 'ProgramData', 'AppData', '$Recycle.Bin', '$RECYCLE.BIN', '$Windows.~WS', '$Windows.~BT', '$SysReset' ] self.vars = { USERPROFILE: os.environ['USERPROFILE'], APPDATA: os.path.normpath(os.path.join(os.environ['APPDATA'], '..')), USERDOC: shell.SHGetFolderPath(0, shellcon.CSIDL_PERSONAL, None, 0) } self.deep = ['*/Steam/steamapps', '*/Steam/userdata'] self.searchpaths = get_drives() if not searchpaths else searchpaths self.tofind = {} self.found = {} self.profiles = {} self.dircache = {} self.itemdict = {} self.lookups = 0
def set_package_location(self, index): if (index > -1): self.packageUrl = self.packageList[index][1] if not self.window.folders(): initialFolder = os.path.expanduser('~') try: from win32com.shell import shellcon, shell initialFolder = shell.SHGetFolderPath( 0, shellcon.CSIDL_APPDATA, 0, 0) except ImportError: initialFolder = os.path.expanduser("~") else: initialFolder = self.window.folders()[0] self.window.show_input_panel( "Select a location to extract the files: ", initialFolder, self.get_package, None, None)
def create_shortcut(folder, name): platform = get_platform() library_folder = Path(get_library_folder()) if platform == 'Windows': targetpath = library_folder / folder / "blender.exe" workingdir = library_folder / folder desktop = shell.SHGetFolderPath(0, shellcon.CSIDL_DESKTOP, None, 0) dist = Path(desktop) / (name + ".lnk") if getattr(sys, 'frozen', False): icon = sys._MEIPASS + "/files/winblender.ico" else: icon = Path( "./resources/icons/winblender.ico").resolve().as_posix() _WSHELL = win32com.client.Dispatch("Wscript.Shell") wscript = _WSHELL.CreateShortCut(dist.as_posix()) wscript.Targetpath = targetpath.as_posix() wscript.WorkingDirectory = workingdir.as_posix() wscript.WindowStyle = 0 wscript.IconLocation = icon wscript.save() elif platform == 'Linux': _exec = library_folder / folder / "blender" icon = library_folder / folder / "blender.svg" desktop = Path.home() / "Desktop" name = name.replace(' ', '-') dist = desktop / (name + ".desktop") desktop_entry = \ "[Desktop Entry]\n" + \ "Name={0}\n".format(name) + \ "Type=Application\n" + \ "Comment={0}\n".format(name) + \ "Terminal=true\n" + \ "Icon={0}\n".format(icon.as_posix().replace(' ', r'\ ')) + \ "Exec=!/bin/bash {0}".format(_exec.as_posix().replace(' ', r'\ ')) with open(dist, 'w') as file: file.write(desktop_entry)
def __init__(self, parent): Frame.__init__(self, parent) self.myParent = parent #self.result_file_suffix = "_wm" #string used to name files that have been watermarked. default will be _wm self.store_location = shell.SHGetFolderPath( 0, shellcon.CSIDL_DESKTOP, None, 0) #a store location (folder) default is desktop #GUI elements self.gui_section1 = LabelFrame( self.myParent, text="Save Options", padx=5, pady=5 ) #LabelFrame is like a fram, but it gives a text and framing line grafically self.store_browse_button = Button(self.gui_section1, text="select save folder", width=16, command=self.store_browse_callback) self.store_location_label = Text( self.gui_section1, bg="lightgrey", width=25, height=1, padx=5, pady=5) #text widget which will show path to storage folder self.file_suffix_input = Entry(self.gui_section1, width=10) self.file_suffix_input.insert(0, "_wm") #labels self.suffix_explanation = Label( self.gui_section1, text="choose a suffix to add to\n the watermarked photo name:") #PLacing in the grid #self.gui_section1.grid() #not necessary, done in the main GUI_App widget self.store_browse_button.grid(row=1, column=2) self.store_location_label.grid(row=1, column=1) self.suffix_explanation.grid(row=0, column=1, sticky=(N, E)) self.file_suffix_input.grid(row=0, column=2, sticky=(S, W)) self.gui_section1.grid_rowconfigure( 1, pad=15 ) #adding some space around the widgets in the row. done by calling its parent (which the rows are in) self.gui_section1.grid_rowconfigure(2, pad=15)
def setup_platform_config(): print "\nSetting up the configuration file:" #gather platform specific data platform_data = {} system = platform.system() config_filedir = None default_config_filepath = None example_calibration_filepath = None print "detected system: %s" % system if system == 'Linux' or system == 'Darwin': if not os.path.isdir(LINUX_AUTOMAT_CONFIG_DIR): os.mkdir(LINUX_AUTOMAT_CONFIG_DIR) config_filedir = LINUX_OLM_PSTAT_CONFIG_DIR if not os.path.isdir(config_filedir): os.mkdir(config_filedir) default_config_filepath = os.sep.join( (config_filedir, DEFAULT_CONFIG_FILENAME)) elif system == 'Windows': from win32com.shell import shellcon, shell appdata_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0) default_config_filepath = os.sep.join( (appdata_path, DEFAULT_CONFIG_FILENAME)) #if the configuration file does NOT exist, than copy the example file to that location if not os.path.isfile(default_config_filepath): print "copying the example config file to '%s', please change these settings to match your system" % default_config_filepath shutil.copy(EXAMPLE_CONFIG_FILENAME, default_config_filepath) else: print "settings file already exists at '%s'; not overwriting; check the documention to see if additional settings are required" % default_config_filepath raw_input("press 'Enter' to continue...") #autogenerate the package information file platform_data['system'] = system platform_data['config_filedir'] = config_filedir platform_data['config_filepath'] = default_config_filepath pkg_info_filename = os.sep.join((MAIN_PACKAGE_PATH, 'pkg_info.py')) pkg_info_file = open(pkg_info_filename, 'w') pkg_info_file.write("metadata = %r\n" % PACKAGE_METADATA) pkg_info_file.write("platform = %r" % platform_data) pkg_info_file.close()
def getShortcutsFile(): """Return the path to the shortcuts file.""" fname = "shortcuts.xml" if sys.platform.startswith("win"): # Favour ~/.go if shortcuts.xml already exists there, otherwise # favour CSIDL_APPDATA/... if have win32com to *find* that dir. dname = os.path.expanduser("~/.go") shortcutsFile = os.path.join(dname, fname) if not os.path.isfile(shortcutsFile): try: from win32com.shell import shellcon, shell dname = os.path.join( shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0), "TrentMick", "Go") shortcutsFile = os.path.join(dname, fname) except ImportError: pass else: dname = os.path.expanduser("~/.go") shortcutsFile = os.path.join(dname, fname) return shortcutsFile
def init_server_directory(): if platform.system() == 'Linux': koi_dir = os.path.join(os.environ['HOME'],'.config', codename) else: try: koi_dir = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "Software\\" + basename.capitalize(), 0,winreg.KEY_READ|winreg.KEY_WOW64_32KEY) koi_dir = winreg.QueryValueEx(k,'base_dir')[0] except: koi_dir = os.path.join( shell.SHGetFolderPath(0, shellcon.CSIDL_COMMON_APPDATA, 0, 0), codename) try: if not os.path.exists(koi_dir): os.makedirs(koi_dir) _root_dir['root_dir'] = koi_dir except: _root_dir['root_dir'] = "."
def _create_desktop_shortcut_windows(frame=None): # Dependency of http://sourceforge.net/projects/pywin32/ import os import sys try: from win32com.shell import shell, shellcon except ImportError: sys.stderr.write("Cannot create desktop shortcut.\nPlease install" " pywin32 from https://github.com/mhammond/pywin32\n" "or pip install pywin32") return False desktop = shell.SHGetFolderPath(0, shellcon.CSIDL_DESKTOP, None, 0) link = os.path.join(desktop, 'RIDE.lnk') public_link = os.path.join(os.getenv('PUBLIC'), 'Desktop', 'RIDE.lnk') icon = os.path.join(sys.prefix, 'Lib', 'site-packages', 'robotide', 'widgets', 'robot.ico') if not (exists(public_link) or exists(link)) or option_f: if not option_q and not option_f: if not _askyesno("Setup", "Create desktop shortcut?", frame): sys.stderr.write( "Users can create a Desktop shortcut to RIDE " "with:\n%s -m robotide.postinstall -install\n" % sys.executable) return False import pythoncom shortcut = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) command_args = " -c \"from robotide import main; main()\"" shortcut.SetPath(sys.executable.replace('python.exe', 'pythonw.exe')) shortcut.SetArguments(command_args) shortcut.SetDescription("Robot Framework testdata editor") shortcut.SetIconLocation(icon, 0) persist_file = shortcut.QueryInterface(pythoncom.IID_IPersistFile) from pywintypes import com_error try: persist_file.Save(public_link, 0) sys.stderr.write(f"Desktop shortcut created for all users.") except com_error: persist_file.Save(link, 0)
def get_network_drives(): if platform.system() == "Linux": return "~/Projects/IBL/github/iblserver" import win32api import win32com.client from win32com.shell import shell, shellcon NETWORK_SHORTCUTS_FOLDER_PATH = shell.SHGetFolderPath(0, shellcon.CSIDL_NETHOOD, None, 0) # Add Logical Drives drives = win32api.GetLogicalDriveStrings() drives = drives.split("\000")[:-1] # Add Network Locations network_shortcuts = [ join(NETWORK_SHORTCUTS_FOLDER_PATH, f) + "\\target.lnk" for f in listdir(NETWORK_SHORTCUTS_FOLDER_PATH) ] shell = win32com.client.Dispatch("WScript.Shell") for network_shortcut in network_shortcuts: shortcut = shell.CreateShortCut(network_shortcut) drives.append(shortcut.Targetpath) return drives