Python Setup implementation code for Windows desktop wallpaper

Source: Internet
Author: User
Tags urlencode
The code is as follows:


#-*-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拉伸适应桌面, 0 Desktop Center
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 (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 (' Download ', H.getsource ())
If R:
Return SendRequest (R[0]). GetSource ()
Else
Print "Error resolving picture address, please check if 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! '


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

The code is as follows:


#!/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:
"""
Web Request Enhancement 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: The content that needs to be post, must be a dictionary
Method:get or Post, default to Get
Auth: ' base ' or ' cookie '
User: Username for base authentication
Password: password for base authentication
Cookie: The cookie that accompanies the request and is generally 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 ' 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/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.__sendrequest ()

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.password = = 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 is 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 for success, 404 for Page Not present)
"""
Return Self.code

def getsource (self):
"""
Get the page source code, need to decode after using
"""
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):
"""
A cookie returned by the server, typically used to log in for subsequent operations
"""
If ' Set-cookie ' in self.head_dict:
Return self.head_dict[' Set-cookie ']
Else
Return None

def getcontenttype (self):
"""
Get 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 encoding of the Web page
If not returned to none
"""
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 Web page 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.baidu.com")
Print B.getsource ()

  • 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.