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实现在sqlite动态创建表的方法
May 08 Python
Python判断字符串与大小写转换
Jun 08 Python
读写json中文ASCII乱码问题的解决方法
Nov 05 Python
python多进程中的内存复制(实例讲解)
Jan 05 Python
通过PHP与Python代码对比的语法差异详解
Jul 10 Python
django框架ModelForm组件用法详解
Dec 11 Python
python实现字符串和数字拼接
Mar 02 Python
Python Tornado批量上传图片并显示功能
Mar 26 Python
python实现启动一个外部程序,并且不阻塞当前进程
Dec 05 Python
Ubuntu20下的Django安装的方法步骤
Jan 24 Python
pytorch 权重weight 与 梯度grad 可视化操作
Jun 05 Python
python工具dtreeviz决策树可视化和模型可解释性
Mar 03 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教程之PHP中shell脚本的使用方法分享
2012/02/23 PHP
PHP实现一维数组转二维数组的方法
2015/02/25 PHP
CI框架出现mysql数据库连接资源无法释放的解决方法
2016/05/17 PHP
document.all还是document.getElementsByName?
2006/07/21 Javascript
慎用 somefunction.prototype 分析
2009/06/02 Javascript
Javascript 继承机制实例
2009/08/12 Javascript
jQuery版仿Path菜单效果
2011/12/15 Javascript
解决jquery插件冲突的问题
2014/01/23 Javascript
jquery查找tr td 示例模拟
2014/05/08 Javascript
js 通过html()及text()方法获取并设置p标签的显示值
2014/05/14 Javascript
jquery实现在网页指定区域显示自定义右键菜单效果
2015/08/25 Javascript
Node.js读写文件之批量替换图片的实现方法
2016/09/07 Javascript
js实现简单的网页换肤效果
2017/01/18 Javascript
js+canvas实现滑动拼图验证码功能
2018/03/26 Javascript
原生JS实现的雪花飘落动画效果
2018/05/03 Javascript
vue使用video插件vue-video-player详解
2020/10/23 Javascript
Nuxt.js的路由跳转操作(页面跳转nuxt-link)
2020/11/06 Javascript
解决vue打包 npm run build-test突然不动了的问题
2020/11/13 Javascript
[06:04]DOTA2国际邀请赛纪录片:Just For LGD
2013/08/11 DOTA
[01:14:41]DOTA2-DPC中国联赛定级赛 iG vs Magma BO3第一场 1月8日
2021/03/11 DOTA
Python3中的真除和Floor除法用法分析
2016/03/16 Python
python中的字符串内部换行方法
2018/07/19 Python
Python使用matplotlib实现交换式图形显示功能示例
2019/09/06 Python
给你一面国旗 教你用python画中国国旗
2019/09/24 Python
Python彻底删除文件夹及其子文件方式
2019/12/23 Python
python3中sorted函数里cmp参数改变详解
2020/03/12 Python
CSS 说明横向进度条最后显示文字的实现代码
2020/11/10 HTML / CSS
英国大码女性时装零售商:Evans
2018/08/29 全球购物
阿玛尼意大利官网:Armani意大利
2018/10/30 全球购物
家长对小学生的评语
2014/01/28 职场文书
2014市府办领导班子“四风问题”对照检查材料思想汇报
2014/09/24 职场文书
后进生评语大全
2015/01/04 职场文书
体育活动总结
2015/02/04 职场文书
老人节主持词
2015/07/04 职场文书
Java基础之详解HashSet的使用方法
2021/06/30 Java/Android
MySQL系列之八 MySQL服务器变量
2021/07/02 MySQL