Python implementation settings for Windows desktop Wallpaper code sharing

Source: Internet
Author: User
Tags urlencode
Every day to change a wallpaper, good mood every day.

#-*-Coding:utf-8-*-from __future__ import unicode_literalsimport imageimport datetimeimport win32gui,win32con,win32a Piimport refrom httpwrapper Import sendrequeststorefolder = "C:\\dayimage" def setwallpaperfrombmp (ImagePath): K = win32a Pi. RegOpenKeyEx (Win32con. HKEY_CURRENT_USER, "Control panel\\desktop", 0,win32con. Key_set_value) Win32API. RegSetValueEx (k, "Wallpaperstyle", 0, Win32con. REG_SZ, "2") #2拉伸适应桌面, 0 desktop centered Win32API. RegSetValueEx (k, "Tilewallpaper", 0, Win32con. REG_SZ, "0") Win32gui. SystemParametersInfo (Win32con.  Spi_setdeskwallpaper,imagepath, 1+2) def setwallpaper (ImagePath): "" "Given a path to an image, convert it to BMP and set it as Wallpaper "" "Bmpimage = Image.open (imagePath) NewPath = Storefolder + ' \\mywallpaper.bmp ' Bmpimage.save (newpat H, "BMP") Setwallpaperfrombmp (NewPath) def getpicture (): url = "Http://photography.nationalgeographic.com/photography    /photo-of-the-day/"h = sendrequest (URL) if H.getsource (): R = Re.findall (' Download ', H.getsource ())If R:return sendrequest (R[0]).  GetSource () else:print "Error parsing picture address, check if regular expression is correct" return Nonedef setwallpaperoftoday (): img = getpicture () if Img:path = Storefolder + "\\%s.jpg"% datetime.date.today () F = open (path, "WB") F.write (IMG) f.close () se Twallpaper (Path) setwallpaperoftoday () print ' wallpaper set ok! '


One of the Httpwrapper I wrote was the encapsulation of an HTTP access:

#!/usr/bin/env python #-*-coding:utf-8-*-#---------------------------------------------------------------------- ---------# Name: Encapsulation of HTTP Access # # author:qianlifeng## created:10-02-2012#--------------------------------------------- ----------------------------------import base64import urllibimport urllib2import timeimport reimport sysclass SendRequest: "" "Web request Enhanced Class 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: Requested URL, cannot be empty date: Required post content, must be dictionary method:get or post, default is Get auth: ' base ' or ' cookie ' User: Username for base authentication PASSW  Ord: Password cookie for base authentication: The cookie that is included with the request, typically used for authentication after login 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 ' refer Er ' 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 = ' M ozilla/5.0 (Windows NT 5.1; rv:8.0) gecko/20100101 firefox/8.0 ' 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.__Send  Request () def __setuprequest (self): If Self.url is None or self.url = = ': Raise ' URL cannot be empty! ' #访问方式设置 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)) #设置认证信息 if Self.auth = = ' base ': if Self.user = None or SELF.PA    ssWOrd = = None:raise ' The user or password is 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 = = ' Cookie ': 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:print "Error:httpwrapper=>_sendrequest", Sys.exc_info () [1] def getresponsecode (self): "" "Get The status code returned by the server (200 indicates success, 404 page does not exist) "" "Return Self.code def GetSource (self):" "" to get the Web page source code, need to decode after using "" "if" source "in Dir (SE LF): Return self.source return u ' def getheaderinfo (self): "" "U ' Get response header message '" "Return self.head_dict def GetCookie (self): "" "gets the cookie returned by the server, typically used to log in subsequent operations" "if" set-cookie ' in Self.head_dict:return self.head_dict[' Set-cookie '] Else:return None def getcontenttype (self): "" "gets returned Back type "" "If ' Content-type ' in Self.head_dict:return self.head_dict[' Content-type '] else:return None def getcharset (self): "" "Try to get the encoding of the Web page if it does not return none" "" ContentType = self. getContentType () If contentType is not None:index = Contenttype.find ("charset") if Index > 0:return conte Nttype[index+8:] Return None def getexpirestime (self): "" "gets the page expiration Time" "" If ' expires ' in the Self.head_dict:return self . head_dict[' Expires ' Else:return None def getservername (self): "" "Get Server Name" "" If ' Server ' in Self.head_dict:r Eturn self.head_dict[' server ' else:return none__all__ = [sendrequest,]if __name__ = ' __main__ ': b = sendrequest ("HT Tp://www.baidu.com ") Print B.getsource ()
  • 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.