def testShellLink(self): desktop = str(shell.SHGetSpecialFolderPath(0, CSIDL_DESKTOP)) num = 0 shellLink = pythoncom.CoCreateInstance( shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink, ) persistFile = shellLink.QueryInterface(pythoncom.IID_IPersistFile) names = [os.path.join(desktop, n) for n in os.listdir(desktop)] programs = str(shell.SHGetSpecialFolderPath(0, CSIDL_PROGRAMS)) names.extend([os.path.join(programs, n) for n in os.listdir(programs)]) for name in names: try: persistFile.Load(name, STGM_READ) except pythoncom.com_error: continue # Resolve is slow - avoid it for our tests. # shellLink.Resolve(0, shell.SLR_ANY_MATCH | shell.SLR_NO_UI) fname, findData = shellLink.GetPath(0) unc = shellLink.GetPath(shell.SLGP_UNCPRIORITY)[0] num += 1 if num == 0: # This isn't a fatal error, but is unlikely. print( "Could not find any links on your desktop or programs dir, which is unusual" )
def get_system_dir(): import win32api # we assume this exists. try: import pythoncom import win32process from win32com.shell import shell, shellcon try: if win32process.IsWow64Process(): return shell.SHGetSpecialFolderPath(0,shellcon.CSIDL_SYSTEMX86) return shell.SHGetSpecialFolderPath(0,shellcon.CSIDL_SYSTEM) except (pythoncom.com_error, win32process.error): return win32api.GetSystemDirectory() except ImportError: return win32api.GetSystemDirectory()
def get_system_directory(): try: from win32com.shell import shell, shellcon return shell.SHGetSpecialFolderPath(0, shellcon.CSIDL_SYSTEM) except Exception, msg: print 'get_system_directory: %s' % (msg) return r'C:\Windows\System32'
def get_windows_directory(): try: from win32com.shell import shell, shellcon return shell.SHGetSpecialFolderPath(0, shellcon.CSIDL_WINDOWS) except Exception, msg: print 'get_windows_directory: %s' % (msg) return r'C:\Windows'
def get_program_files_directory(): try: from win32com.shell import shell, shellcon return shell.SHGetSpecialFolderPath(0, shellcon.CSIDL_PROGRAM_FILES) except Exception, msg: print 'get_program_files_directory: %s' % (msg) return r'C:\Program Files'
def _get_sh_special_folder_path(csidl): """Call SHGetSpecialFolderPathW if available, or return None. Result is always unicode (or None). """ if has_ctypes: try: SHGetSpecialFolderPath = \ ctypes.windll.shell32.SHGetSpecialFolderPathW except AttributeError: pass else: buf = ctypes.create_unicode_buffer(MAX_PATH) if SHGetSpecialFolderPath(None, buf, csidl, 0): return buf.value global has_win32com_shell if has_win32com_shell is None: try: from win32com.shell import shell has_win32com_shell = True except ImportError: has_win32com_shell = False if has_win32com_shell: # still need to bind the name locally, but this is fast. from win32com.shell import shell try: return shell.SHGetSpecialFolderPath(0, csidl, 0) except shell.error: # possibly E_NOTIMPL meaning we can't load the function pointer, # or E_FAIL meaning the function failed - regardless, just ignore it pass return None
def get_special_folder_path(path_name): try: import pythoncom except ImportError: print("pywin32 is required to run this script manually", file=sys.stderr) sys.exit(1) from win32com.shell import shell, shellcon path_names = [ "CSIDL_COMMON_STARTMENU", "CSIDL_STARTMENU", "CSIDL_COMMON_APPDATA", "CSIDL_LOCAL_APPDATA", "CSIDL_APPDATA", "CSIDL_COMMON_DESKTOPDIRECTORY", "CSIDL_DESKTOPDIRECTORY", "CSIDL_COMMON_STARTUP", "CSIDL_STARTUP", "CSIDL_COMMON_PROGRAMS", "CSIDL_PROGRAMS", "CSIDL_PROGRAM_FILES_COMMON", "CSIDL_PROGRAM_FILES", "CSIDL_FONTS", ] for maybe in path_names: if maybe == path_name: csidl = getattr(shellcon, maybe) return shell.SHGetSpecialFolderPath(0, csidl, False) raise ValueError("%s is an unknown path ID" % (path_name, ))
def get_autostart_path(): """Return the path of the BleachBit shortcut in the user's startup folder""" try: startupdir = shell.SHGetSpecialFolderPath(None, shellcon.CSIDL_STARTUP) except: # example of failure # https://www.bleachbit.org/forum/error-windows-7-x64-bleachbit-091 logger = logging.getLogger(__name__) logger.exception('exception in get_autostart_path()') msg = 'Error finding user startup folder: %s ' % (str( sys.exc_info()[1])) import GuiBasic GuiBasic.message_dialog(None, msg) # as a fallback, guess # Windows XP: C:\Documents and Settings\(username)\Start Menu\Programs\Startup # Windows 7: # C:\Users\(username)\AppData\Roaming\Microsoft\Windows\Start # Menu\Programs\Startup startupdir = os.path.expandvars( '$USERPROFILE\\Start Menu\\Programs\\Startup') if not os.path.exists(startupdir): startupdir = os.path.expandvars( '$APPDATA\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup' ) return os.path.join(startupdir, 'bleachbit.lnk')
def pathToDocumentsDir(): if operating_system.isWindows(): from win32com.shell import shell, shellcon try: return shell.SHGetSpecialFolderPath(None, shellcon.CSIDL_PERSONAL) except: # Yes, one of the documented ways to get this sometimes fail with "Unspecified error". Not sure # this will work either. # Update: There are cases when it doesn't work either; see support request #410... try: return shell.SHGetFolderPath(None, shellcon.CSIDL_PERSONAL, None, 0) # SHGFP_TYPE_CURRENT not in shellcon except: return os.getcwd() # F**k this elif operating_system.isMac(): import Carbon.Folder, Carbon.Folders, Carbon.File pathRef = Carbon.Folder.FSFindFolder(Carbon.Folders.kUserDomain, Carbon.Folders.kDocumentsFolderType, True) return Carbon.File.pathname(pathRef) elif operating_system.isGTK(): try: from PyKDE4.kdeui import KGlobalSettings except ImportError: pass else: return unicode(KGlobalSettings.documentPath()) # Assuming Unix-like return os.path.expanduser('~')
def get_appdata_directory(): try: from win32com.shell import shell, shellcon return shell.SHGetSpecialFolderPath(0, shellcon.CSIDL_APPDATA) except Exception, msg: print 'get_appdata_directory: %s' % (msg) return ''
def __init__(self): super(Recent, self).__init__() self._paths = [] # http://python.6.n6.nabble.com/Access-Most-Recently-Used-MRU-entries-td1953541.html self.mru_path = shell.SHGetSpecialFolderPath(0, shellcon.CSIDL_RECENT, 0) self.mrufs = OSFS(self.mru_path) self.watcher = None
def environ(varname, csidl): try: os.environ[varname] = shell.SHGetSpecialFolderPath(None, csidl) except: traceback.print_exc() msg = 'Error setting environemnt variable "%s": %s ' % ( varname, str(sys.exc_info()[1])) import GuiBasic GuiBasic.message_dialog(None, msg)
def csidl_to_environ(varname, csidl): """Define an environment variable from a CSIDL for use in CleanerML and Winapp2.ini""" try: sppath = shell.SHGetSpecialFolderPath(None, csidl) except: logger.info('exception when getting special folder path for %s', varname) return # there is exception handling in set_environ() set_environ(varname, sppath)
def pathToStartMenuShortcut(filename): try: from win32com.shell import shell, shellcon from win32com.client import Dispatch shell_ = Dispatch('WScript.Shell') csidl = getattr(shellcon, 'CSIDL_PROGRAMS') startmenu = shell.SHGetSpecialFolderPath(0, csidl, False) return os.path.join(startmenu, filename) except Error as e: print("pathToStartMenuShortcut(1) {0}".format(e)) return ''
def environ(varname, csidl): if os.environ.has_key(varname): # Do not redefine the environment variable when it already exists return try: os.environ[varname] = shell.SHGetSpecialFolderPath(None, csidl) except: import traceback traceback.print_exc() print 'ERROR: setting environment variable "%s": %s ' % ( varname, str(sys.exc_info()[1]))
def get_special_folder_path(path_name): """Return special folder path""" from win32com.shell import shell, shellcon for maybe in """ CSIDL_COMMON_STARTMENU CSIDL_STARTMENU CSIDL_COMMON_APPDATA CSIDL_LOCAL_APPDATA CSIDL_APPDATA CSIDL_COMMON_DESKTOPDIRECTORY CSIDL_DESKTOPDIRECTORY CSIDL_COMMON_STARTUP CSIDL_STARTUP CSIDL_COMMON_PROGRAMS CSIDL_PROGRAMS CSIDL_PROGRAM_FILES_COMMON CSIDL_PROGRAM_FILES CSIDL_FONTS""".split(): if maybe == path_name: csidl = getattr(shellcon, maybe) return shell.SHGetSpecialFolderPath(0, csidl, False) raise ValueError("%s is an unknown path ID" % (path_name, ))
def RemoveShortcuts(hwnd, setupWindows): try: if (win32gui.GetClassName(hwnd), win32gui.GetWindowText(hwnd)) in setupWindows: # delete leftover ClamWin shortcuts CSIDL_COMMON_PROGRAMS and CSIDL_PROGRAMS # C:\Documents and Settings\All Users\Start Menu\Programs\ClamWin Antivirus s = shell.SHGetSpecialFolderPath(0, shellcon.CSIDL_COMMON_PROGRAMS, True) s = os.path.join(s, 'ClamWin Antivirus') s = os.path.join(s, 'Quarantine Browser.lnk') try: os.remove(s) except: pass s = shell.SHGetSpecialFolderPath(0, shellcon.CSIDL_PROGRAMS, True) s = os.path.join(s, 'ClamWin Antivirus') s = os.path.join(s, 'Quarantine Browser.lnk') try: os.remove(s) except: pass except Exception, e: print 'RemoveShortcuts exception', str(e)
def _get_path(self, appname): if os.name == 'nt': try: import pywintypes try: from win32com.shell import shell, shellcon appdir = shell.SHGetSpecialFolderPath( 0, shellcon.CSIDL_APPDATA) except pywintypes.com_error: appdir = os.environ['APPDATA'] except ImportError: appdir = os.environ['APPDATA'] return os.path.join(appdir, 'TortoiseHg', appname) else: home = os.path.expanduser('~') return os.path.join(home, '.tortoisehg', appname)
def createStartMenuShortcut(filename, target='', wDir='', icon='', args=''): try: from win32com.shell import shell, shellcon from win32com.client import Dispatch shell_ = Dispatch('WScript.Shell') csidl = getattr(shellcon, 'CSIDL_PROGRAMS') startmenu = shell.SHGetSpecialFolderPath(0, csidl, False) path = os.path.join(startmenu, filename) shortcut = shell_.CreateShortCut(path) shortcut.Targetpath = target shortcut.WorkingDirectory = wDir shortcut.Arguments = args if icon != '': shortcut.IconLocation = icon shortcut.save() except Error as e: print("createStartMenuShortcut(1) {0}".format(e))
def pathToConfigDir(self, environ): try: if operating_system.isGTK(): from taskcoachlib.thirdparty.xdg import BaseDirectory path = BaseDirectory.save_config_path(meta.name) elif operating_system.isMac(): import Carbon.Folder, Carbon.Folders, Carbon.File pathRef = Carbon.Folder.FSFindFolder(Carbon.Folders.kUserDomain, Carbon.Folders.kPreferencesFolderType, True) path = Carbon.File.pathname(pathRef) # XXXFIXME: should we release pathRef ? Doesn't seem so since I get a SIGSEGV if I try. elif operating_system.isWindows(): from win32com.shell import shell, shellcon path = os.path.join(shell.SHGetSpecialFolderPath(None, shellcon.CSIDL_APPDATA, True), meta.name) else: path = self.pathToConfigDir_deprecated(environ=environ) except: # Fallback to old dir path = self.pathToConfigDir_deprecated(environ=environ) return path
def configFile(): if platform.startswith("win") or name == "nt": try: import pywintypes try: from win32com.shell import shell, shellcon appdata = shell.SHGetSpecialFolderPath(0, \ shellcon.CSIDL_APPDATA) except pywintypes.com_error: appdata = environ['APPDATA'] except ImportError: appdata = path.join(environ['APPDATA'], ) else: appdata = path.expanduser(path.join("~", ".config/")) appdata = unicode(appdata) #appdata = QDesktopServices.storageLocation(QDesktopServices.DataLocation) #config = unicode(appdata + QDir.separator() + conFile') return path.join(appdata, APPGROUP, conFile)
def get_vmware_default_vm_path(): """ Returns VMware default VM directory path. :returns: path to the default VM directory """ if sys.platform.startswith("win"): from win32com.shell import shell, shellcon documents_folder = shell.SHGetSpecialFolderPath( None, shellcon.CSIDL_PERSONAL) windows_type = sys.getwindowsversion().product_type if windows_type == 2 or windows_type == 3: return '{}\My Virtual Machines'.format(documents_folder) else: return '{}\Virtual Machines'.format(documents_folder) elif sys.platform.startswith("darwin"): return os.path.expanduser("~/Documents/Virtual Machines.localized") else: return os.path.expanduser("~/vmware")
def _pathToDataDir(self, *args, **kwargs): forceGlobal = kwargs.pop('forceGlobal', False) if operating_system.isGTK(): from taskcoachlib.thirdparty.xdg import BaseDirectory path = BaseDirectory.save_data_path(meta.name) elif operating_system.isMac(): import Carbon.Folder, Carbon.Folders, Carbon.File pathRef = Carbon.Folder.FSFindFolder( Carbon.Folders.kUserDomain, Carbon.Folders.kApplicationSupportFolderType, True) path = Carbon.File.pathname(pathRef) # XXXFIXME: should we release pathRef ? Doesn't seem so since I get a SIGSEGV if I try. path = os.path.join(path, meta.name) elif operating_system.isWindows(): if self.__iniFileSpecifiedOnCommandLine and not forceGlobal: path = self.pathToIniFileSpecifiedOnCommandLine() else: from win32com.shell import shell, shellcon path = os.path.join( shell.SHGetSpecialFolderPath(None, shellcon.CSIDL_APPDATA, True), meta.name) else: # Errr... path = self.path() if operating_system.isWindows(): # Follow shortcuts. from win32com.client import Dispatch shell = Dispatch('WScript.Shell') for component in args: path = os.path.join(path, component) if os.path.exists(path + '.lnk'): shortcut = shell.CreateShortcut(path + '.lnk') path = shortcut.TargetPath else: path = os.path.join(path, *args) exists = os.path.exists(path) if not exists: os.makedirs(path) return path, exists
def GetProfileDir(bUnicode): try: if sys.platform.startswith("win"): # read template config file conf = Config.Settings( os.path.join(GetCurrentDir(bUnicode), 'ClamWin.conf')) if conf.Read(template=True) and conf.Get('UI', 'Standalone') == '1': profileDir = GetCurrentDir(bUnicode) else: profileDir = shell.SHGetSpecialFolderPath( 0, shellcon.CSIDL_APPDATA, True) profileDir = os.path.join(profileDir, '.clamwin') # change encoding to proper unicode if bUnicode: profileDir = pywintypes.Unicode(profileDir) else: profileDir = os.path.join(os.path.expanduser('~'), '.clamwin') except Exception, e: print 'Could not get the profile folder. Error: %s' % str(e) profileDir = GetCurrentDir(bUnicode)
def post_install(): """ Windows post install function. """ try: desktop = shell.SHGetSpecialFolderPath(0, CSIDL_DESKTOP) prefix = sys.prefix if '--user' in sys.argv: siteP = [n for n in sys.path if 'site-packages' in os.path.split(n)[1]] for p in siteP: prefix = os.path.split(p)[0] if os.path.isfile(os.path.join(prefix, "Scripts", "aview.exe")): break script = os.path.join(prefix, "Scripts", "aview.exe") if not os.path.isfile(script): raise FileNotFoundError dpt = Dispatch('WScript.Shell') sh = dpt.CreateShortcut(os.path.join(desktop, "ArrayViewer.lnk")) sh.Targetpath = script sh.WorkingDirectory = os.path.split(script)[0] sh.save() except: print("No shortcut created!")
def special_folder(folder_id): return shell.SHGetSpecialFolderPath(None, CSIDL.constant(folder_id), 0)
def getpath(csidl): return shell.SHGetSpecialFolderPath(None, csidl, 0)
def getMenuPath(): path = shell.SHGetSpecialFolderPath(0, shellcon.CSIDL_STARTMENU) if os.path.exists(path): return path else: return None
def DumpFavorites(): favfold = str(shell.SHGetSpecialFolderPath(0, shellcon.CSIDL_FAVORITES)) print("Your favourites are at", favfold) os.path.walk(favfold, FavDumper, None)
def _getApplicationDataDirectory(self): appData = shell.SHGetSpecialFolderPath(0, shellcon.CSIDL_APPDATA, False) path = os.path.join(appData, u"Zoundry/Zoundry Raven") #$NON-NLS-1$ return path