Set windows desktop wallpaper in python

Source: Internet
Author: User
Tags bmp image

Change a wallpaper every day and make a good mood every day.
 
#-*-Coding: UTF-8 -*-

From _ future _ import unicode_literals
Import Image
Import datetime
Import win32gui, win32con, win32api
Import re
From HttpWrapper import SendRequest

StoreFolder = "c: \ dayImage"

Def setWallpaperFromBMP (imagepath ):
K = win32api. RegOpenKeyEx (win32con. HKEY_CURRENT_USER, "Control Panel \ Desktop", 0, win32con. KEY_SET_VALUE)
Win32api. RegSetValueEx (k, "WallpaperStyle", 0, win32con. REG_SZ, "2") #2 stretch fit desktop, 0 desktop Center
Win32api. RegSetValueEx (k, "TileWallpaper", 0, win32con. REG_SZ, "0 ")
Win32gui. SystemParametersInfo (win32con. spi_set1_wallpaper, imagepath, 1 + 2)

Def setWallPaper (imagePath ):
"""
Given a path to an image, convert it to bmp and set it as wallpaper
"""
BMP Image = Image. open (imagePath)
NewPath = StoreFolder + '\ mywallpaper.bmp'
BMP image. save (newPath, "BMP ")
SetWallpaperFromBMP (newPath)

Def getPicture ():
Url = "http://photography.nationalgeographic.com/photography/photo-of-the-day"
H = SendRequest (url)
If h. GetSource ():
R = re. findall ('<div class = "download_link"> <a href = "(.*?) "> Download ', h. GetSource ())
If r:
Return SendRequest (r [0]). GetSource ()
Else:
Print "An error occurred while parsing the image address. Check whether the regular expression is correct"
Return None


Def setWallpaperOfToday ():
Img = getPicture ()
If img:
Path = StoreFolder + "\ % s.jpg" % datetime. date. today ()
F = open (path, "wb ")
F. write (img)
F. close ()
SetWallPaper (path)

SetWallpaperOfToday ()
Print 'wallpaper set OK! '
 
 
The httpwrapper is an http access encapsulation I wrote:
 
#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-
#-------------------------------------------------------------------------------
# Name: encapsulation of http access
#
# Author: qianlifeng
#
# Created: 10-02-2012
#-------------------------------------------------------------------------------

Import base64
Import urllib
Import urllib2
Import time
Import re
Import sys

Class SendRequest:
"""
Webpage request Enhancement
SendRequest ('HTTP: // xxx.com ', data = dict, type = 'post', auth = 'base', user = 'xxx', password = 'xxx ')
"""
Def _ init _ (self, url, data = None, method = 'get', auth = None, user = None, password = None, cookie = None, ** header ):
"""
Url: the requested url. It cannot be blank.
Date: the content to be post. It must be a dictionary.
Method: Get or Post. The default value is Get.
Auth: 'base' or 'cooker'
User: user name used for base authentication
Password: password used for base authentication
Cookie: the cookie attached to the request. It is generally used for post-login authentication.
Other header information:
E.g. referer = 'www .sina.com.cn'
"""

Self. url = url
Self. data = data
Self. method = method
Self. auth = auth
Self. user = user
Self. password = password
Self. cookie = cookie

If 'Referer' in header:
Self. referer = header [referer]
Else:
Self. referer = None

If 'user-agent' in header:
Self. user_agent = header [user-agent]
Else:
# Self. user_agent = 'mozilla/5.0 (Windows NT 5.1; rv: 8.0) Gecko/20100101 Firefox/123456'
Self. user_agent = 'mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) version/4.0 Mobile/7A341 Safari/528.16'

Self. _ SetupRequest ()
Self. _ SendRequest ()

Def _ SetupRequest (self ):

If self. url is None or self. url = '':
Raise 'url cannot be blank! '

# Access method settings
If self. method. lower () = 'post ':
Self. Req = urllib2.Request (self. url, urllib. urlencode (self. data ))

Elif self. method. lower () = 'get ':
If self. data = None:
Self. Req = urllib2.Request (self. url)
Else:
Self. Req = urllib2.Request (self. url + '? '+ Urllib. urlencode (self. data ))

# Set authentication information
If self. auth = 'base ':
If self. user = None or self. password = None:
Raise 'the user or password was not given! '
Else:
Auth_info = base64.encodestring (self. user + ':' + self. password). replace ('\ n ','')
Auth_info = 'basic '+ auth_info
Self. Req. add_header ("Authorization", auth_info)

Elif self. auth = 'cooker ':
If self. cookie = None:
Raise 'the cookie was not given! '
Else:
Self. Req. add_header ("Cookie", self. cookie)


If self. referer:
Self. Req. add_header ('Referer', self. referer)
If self. user_agent:
Self. Req. add_header ('user-agent', self. user_agent)


Def _ SendRequest (self ):

Try:
Self. Res = urllib2.urlopen (self. Req)
Self. source = self. Res. read ()
Self. code = self. Res. getcode ()
Self. head_dict = self.Res.info (). dict
Self. Res. close ()
Except t:
Print "Error: HttpWrapper => _ SendRequest", sys. exc_info () [1]


Def GetResponseCode (self ):
"""
Get the status code returned by the server (200 indicates success, and 404 page does not exist)
"""
Return self. code

Def GetSource (self ):
"""
Obtain the webpage source code, which must be decoded before use
"""
If "source" in dir (self ):
Return self. source
Return u''

Def GetHeaderInfo (self ):
"""
U'get Response Header information'
"""
Return self. head_dict

Def GetCookie (self ):
"""
Obtain the Cookie returned by the server, which is generally used for subsequent login operations.
"""
If 'set-cookies' in self. head_dict:
Return self. head_dict ['set-cooker']
Else:
Return None

Def GetContentType (self ):
"""
Return type
"""
If 'content-type' in self. head_dict:
Return self. head_dict ['content-type']
Else:
Return None

Def GetCharset (self ):
"""
Try to get the webpage code
If None is not returned
"""
ContentType = self. GetContentType ()
If contentType is not None:
Index = contentType. find ("charset ")
If index> 0:
Return contentType [index + 8:]
Return None

Def GetExpiresTime (self ):
"""
Get the webpage expiration time
"""
If 'expires' in self. head_dict:
Return self. head_dict ['expires']
Else:
Return None

Def GetServerName (self ):
"""
Get the server name
"""
If 'server' in self. head_dict:
Return self. head_dict ['server']
Else:
Return None

_ All _ = [SendRequest,]

If _ name _ = '_ main __':
B = SendRequest ("http://www.bkjia.com ")
Print B. GetSource ()

 

 

From Qian lifeng's blog

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.