Working with the Windows Registry
Larry Bates
larry.bates at websafe.com`
Wed Jun 25 23:30:35 EDT 2008
teh_sAbEr wrote:
> Hi everybody. I'm trying to write a script that'll change desktop
> wallpaper every time its run. Heres what I've gotten so far:
>
> #random wallpaper changer!
> import _winreg
> from os import walk
> from os.path import exists
> from random import randint
>
> #first grab a registry handle.
> handle = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,'Control Panel
> \Desktop',_winreg.KEY_SET_VALUE)
>
> def GenerateListOfWallpapers():
> targetDir = 'C:\Documents and Settings\Enrico Jr\My Documents\Jr
> \'s Wallpapers'
> fileNames = []
> filePaths = []
> if exists(targetDir):
> #proceed to make the list of files
> for x,y,z in walk(targetDir):
> for name in z:
> fileNames.append(name)
> for item in fileNames:
> filePaths.append(targetDir + '\\' + item)
> return filePaths
>
> def RandomlySelectWallpaper(filePaths):
> index = randint(0,len(filePaths)-1)
> RandomlySelectedWallpaper = filePaths[index]
> return RandomlySelectedWallpaper #it should be a string...
>
> #now to edit the wallpaper registry key
> newWallpaper = RandomlySelectWallpaper(GenerateListOfWallpapers())
> print "Registry Handle Created."
> print "Random wallpaper selected."
> _winreg.SetValueEx(handle,'ConvertedWallpaper',
> 0,_winreg.REG_SZ,newWallpaper)
> print "New wallpaper value set."
>
> The problem is, every time I run it, I get an "Access Denied" error
> when it tries to execute
> _winreg.SetValueEx(), even though i've opened the key with the
> KEY_SET_VALUE mask like it said in the help docs. Could there be
> another problem or a better way to do this?
Common error. You have to open the key so that it can be written as follows:
reg = _winreg.HKEY_CURRENT_USER
key = r'Control Panel\Desktop'
handle = _winreg.OpenKey(reg, key, 0, _winreg.KEY_WRITE)
Note: be careful with backslashes (\) in non-raw strings they will be
interpreted as escaped sequences. You were lucky because \D doesn't
represent anything escaped. You should either use r's\gg\gg' or use double
backslashes 's\\gg\\gg'.
-Larry
More information about the Python-list
mailing list