Python scripts

From Datateknik
Revision as of 14:42, 1 November 2019 by Imra (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Intro

Contents

Wallpaper background CPU-info

= 1. regedt32 and PyWin http://www.blog.pythonlibrary.org/2014/10/22/pywin32-how-to-set-desktop-background/

For the first approach, you will need to go download a copy of PyWin32 and install it. Now let’s look at the code:

# based on http://dzone.com/snippets/set-windows-desktop-wallpaper
import win32api, win32con, win32gui
 
#----------------------------------------------------------------------
def setWallpaper(path):
   key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\\Desktop",0,win32con.KEY_SET_VALUE)
   win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "0")
   win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0")
   win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, path, 1+2)

if __name__ == "__main__":
   path = r'C:\Users\Public\Pictures\Sample Pictures\Jellyfish.jpg'
   setWallpaper(path)

In this example, we use a sample image that Microsoft provides with Windows. In the code above, we eidt a Windows Registry key. You could do the first 3 lines using Python’s own _winreg module if you wanted to. The last line tells Windows to set the desktop to the image we provided.

2. ctypes http://www.blog.pythonlibrary.org/2014/10/22/pywin32-how-to-set-desktop-background/

Now let’s look at another approach that utilizes the ctypes module and PyWin32.

import ctypes
import win32con
 
def setWallpaperWithCtypes(path):
   # This code is based on the following two links
   # http://mail.python.org/pipermail/python-win32/2005-January/002893.html
   # http://code.activestate.com/recipes/435877-change-the-wallpaper-under-windows/
   cs = ctypes.c_buffer(path)
   ok = ctypes.windll.user32.SystemParametersInfoA(win32con.SPI_SETDESKWALLPAPER, 0, cs, 0)
 
if __name__ == "__main__":
   path = r'C:\Users\Public\Pictures\Sample Pictures\Jellyfish.jpg'
   setWallpaperWithCtypes(path)

In this piece of code, we create a buffer object that we then pass to basically the same command as we did in the previous example, namely SystemParametersInfoA. You will note that we don’t need to edit the registry in this latter case. If you check out the links listed in the sample code, you will note that some users found that Windows XP only allowed bitmaps to be set as the desktop background. I tested with a JPEG on Windows 7 and it worked fine for me.

More stuff

Personal tools
Namespaces

Variants
Actions
Navigation
Tools