欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python设置windows桌面壁纸的实现代码

程序员文章站 2022-12-27 08:50:05
复制代码 代码如下:# -*- coding: utf-8 -*- from __future__ import unicode_literalsimport imag...

复制代码 代码如下:

# -*- 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桌面居中
    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('<div class="download_link"><a href="(.*?)">download',h.getsource())
        if r:
            return sendrequest(r[0]).getsource()
        else:
            print "解析图片地址出错,请检查正则表达式是否正确"
            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!'


其中的httpwrapper是我写的一个http访问的封装:
复制代码 代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# name: 对http访问的封装
#
# author: qianlifeng
#
# created: 10-02-2012
#-------------------------------------------------------------------------------

import base64
import urllib
import urllib2
import time
import re
import sys

class sendrequest:
  """
  网页请求增强类
  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: 请求的url,不能为空
    date: 需要post的内容,必须是字典
    method: get 或者 post,默认为get
    auth: 'base' 或者 'cookie'
    user: 用于base认证的用户名
    password: 用于base认证的密码
    cookie: 请求附带的cookie,一般用于登录后的认证
    其他头信息:
    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 不能为空!'

    #访问方式设置
    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 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 == '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):
    """
    得到服务器返回的状态码(200表示成功,404网页不存在)
    """
    return self.code

  def getsource(self):
    """
    得到网页源代码,需要解码后在使用
    """
    if "source" in dir(self):
        return self.source
    return u''

  def getheaderinfo(self):
    """
    u'得到响应头信息'
    """
    return self.head_dict

  def getcookie(self):
    """
    得到服务器返回的cookie,一般用于登录后续操作
    """
    if 'set-cookie' in self.head_dict:
      return self.head_dict['set-cookie']
    else:
      return none

  def getcontenttype(self):
    """
    得到返回类型
    """
    if 'content-type' in self.head_dict:
      return self.head_dict['content-type']
    else:
      return none

  def getcharset(self):
    """
    尝试得到网页的编码
    如果得不到返回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):
    """
    得到网页过期时间
    """
    if 'expires' in self.head_dict:
      return self.head_dict['expires']
    else:
      return none

  def getservername(self):
    """
    得到服务器名字
    """
    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()