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定时采集摄像头图像上传ftp服务器功能实现
Dec 23 Python
Python下的twisted框架入门指引
Apr 15 Python
Python的“二维”字典 (two-dimension dictionary)定义与实现方法
Apr 27 Python
python 获取文件下所有文件或目录os.walk()的实例
Apr 23 Python
python numpy和list查询其中某个数的个数及定位方法
Jun 27 Python
Python面向对象程序设计中类的定义、实例化、封装及私有变量/方法详解
Feb 28 Python
解决Django中多条件查询的问题
Jul 18 Python
python 3.6.7实现端口扫描器
Sep 04 Python
python字符串下标与切片及使用方法
Feb 13 Python
Python动态导入模块和反射机制详解
Feb 18 Python
2021年值得向Python开发者推荐的VS Code扩展插件
Jan 25 Python
python文件目录操作之os模块
May 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
基于HTTP长连接的&quot;服务器推&quot;技术的php 简易聊天室
2009/10/31 PHP
php异步多线程swoole用法实例
2014/11/14 PHP
PHP递归复制、移动目录的自定义函数分享
2014/11/18 PHP
PHP中substr()与explode()函数用法分析
2014/11/24 PHP
PHP实现在windows下配置sendmail并通过mail()函数发送邮件的方法
2017/06/20 PHP
PHP Post获取不到非表单数据的问题解决办法
2018/02/27 PHP
js使用removeChild方法动态删除div元素
2014/08/01 Javascript
谈谈AngularJs中的隐藏和显示
2015/12/09 Javascript
jQuery图片左右滚动代码 有左右按钮实例
2016/06/20 Javascript
bootstrap下拉菜单使用方法解析
2017/01/13 Javascript
javascript实现滑动解锁功能
2017/03/22 Javascript
ES6新特性之解构、参数、模块和记号用法示例
2017/04/01 Javascript
基于JavaScript实现的折半查找算法示例
2017/04/14 Javascript
本地搭建微信小程序服务器的实现方法
2017/10/27 Javascript
sublime text配置node.js调试(图文教程)
2017/11/23 Javascript
浅谈vue首屏加载优化
2018/06/28 Javascript
js中getter和setter用法实例分析
2018/08/14 Javascript
基于js Canvas实现二次贝塞尔曲线
2018/12/25 Javascript
vue 实现特定条件下绑定事件
2019/11/09 Javascript
微信小程序 button样式设置为图片的方法
2020/06/19 Javascript
jQuery实现异步上传一个或多个文件
2020/08/17 jQuery
Python图形绘制操作之正弦曲线实现方法分析
2017/12/25 Python
python实现简单登陆流程的方法
2018/04/22 Python
Python http接口自动化测试框架实现方法示例
2018/12/06 Python
详解Python time库的使用
2019/10/10 Python
python修改文件内容的3种方法详解
2019/11/15 Python
Python使用qrcode二维码库生成二维码方法详解
2020/02/17 Python
解决启动django,浏览器显示“服务器拒绝访问”的问题
2020/05/13 Python
Python使用Opencv实现边缘检测以及轮廓检测的实现
2020/12/31 Python
python中的unittest框架实例详解
2021/02/05 Python
EJB包括(SessionBean,EntityBean)说出他们的生命周期,及如何管理事务的
2015/07/24 面试题
劳动竞赛口号
2014/06/16 职场文书
四风问题班子对照检查材料
2014/09/27 职场文书
党员“四风”问题批评与自我批评思想汇报
2014/10/06 职场文书
《假如》教学反思
2016/02/17 职场文书
CSS的class与id常用的命名规则
2021/05/18 HTML / CSS