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


Posted in Python onJanuary 28, 2013
# -*- 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()
Python 相关文章推荐
介绍Python中的一些高级编程技巧
Apr 02 Python
简单介绍Python中的RSS处理
Apr 13 Python
python入门教程之识别验证码
Mar 04 Python
Python实现读写sqlite3数据库并将统计数据写入Excel的方法示例
Aug 07 Python
Python基于辗转相除法求解最大公约数的方法示例
Apr 04 Python
基于Django框架利用Ajax实现点赞功能实例代码
Aug 19 Python
Python处理时间日期坐标轴过程详解
Jun 25 Python
django 使用全局搜索功能的实例详解
Jul 18 Python
如何使用Python抓取网页tag操作
Feb 14 Python
pyinstaller打包找不到文件的问题解决
Apr 15 Python
python如何调用字典的key
May 25 Python
python画图时设置分辨率和画布大小的实现(plt.figure())
Jan 08 Python
python连接sql server乱码的解决方法
Jan 28 #Python
python定时检查启动某个exe程序适合检测exe是否挂了
Jan 21 #Python
Python实现的金山快盘的签到程序
Jan 17 #Python
多线程爬虫批量下载pcgame图片url 保存为xml的实现代码
Jan 17 #Python
Python高效编程技巧
Jan 07 #Python
Python内置函数bin() oct()等实现进制转换
Dec 30 #Python
python的id()函数解密过程
Dec 25 #Python
You might like
PHP 第二节 数据类型之数组
2012/04/28 PHP
symfony2.4的twig中date用法分析
2016/03/18 PHP
PHP基于PDO实现的SQLite操作类【包含增删改查及事务等操作】
2017/06/21 PHP
PHP htmlspecialchars()函数用法与实例讲解
2019/03/08 PHP
PHP中__set()实例用法和基础讲解
2019/07/23 PHP
基于jQuery判断两个元素是否有重叠部分的代码
2012/07/25 Javascript
自动设置iframe大小的jQuery代码
2013/09/11 Javascript
前台js调用后台方法示例
2013/12/02 Javascript
jQuery写fadeTo示例代码
2014/02/21 Javascript
jQuery遍历页面所有CheckBox查看是否被选中的方法
2015/04/14 Javascript
JavaScript中Date.toSource()方法的使用教程
2015/06/12 Javascript
js实现选中复选框文字变色的方法
2015/08/14 Javascript
jQuery链式操作实例分析
2015/11/16 Javascript
全面解析Bootstrap表单使用方法(表单控件状态)
2015/11/24 Javascript
使用Bootstrap美化按钮实例代码(demo)
2017/02/03 Javascript
vue.js与element-ui实现菜单树形结构的解决方法
2018/04/21 Javascript
利用百度echarts实现图表功能简单入门示例【附源码下载】
2019/06/10 Javascript
python重试装饰器示例
2014/02/11 Python
手动实现把python项目发布为exe可执行程序过程分享
2014/10/23 Python
Python中使用Queue和Condition进行线程同步的方法
2016/01/19 Python
Python中字典(dict)合并的四种方法总结
2017/08/10 Python
浅谈pycharm下找不到sqlalchemy的问题
2018/12/03 Python
Python OpenCV利用笔记本摄像头实现人脸检测
2020/08/20 Python
python自动发邮件总结及实例说明【推荐】
2019/05/31 Python
Pyqt5自适应布局实例
2019/12/13 Python
GAP阿联酋官网:GAP UAE
2017/11/30 全球购物
手工制作的男士奢华英国鞋和服装之家:Goodwin Smith
2019/06/21 全球购物
Arti-shopping中文官网:大型海外商品一站式直邮平台
2020/03/23 全球购物
前台文员的岗位职责
2013/11/14 职场文书
小车司机岗位职责
2013/11/25 职场文书
赞美老师的演讲稿
2014/05/22 职场文书
股东出资证明书(正规版)
2014/09/24 职场文书
居委会个人对照检查材料思想汇报
2014/09/29 职场文书
劳动纠纷调解协议书格式
2014/11/30 职场文书
公司2015年终工作总结
2015/05/26 职场文书
投诉书格式范本
2015/07/02 职场文书