Python实现设置windows桌面壁纸代码分享


Posted in Python onMarch 28, 2015

每天换一个壁纸,每天好心情。

# -*- 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进程类subprocess的一些操作方法例子
Nov 22 Python
python itchat实现微信好友头像拼接图的示例代码
Aug 14 Python
python读取文本中数据并转化为DataFrame的实例
Apr 10 Python
转换科学计数法的数值字符串为decimal类型的方法
Jul 16 Python
基于python实现名片管理系统
Nov 30 Python
numpy.array 操作使用简单总结
Nov 08 Python
python实现简单日志记录库glog的使用
Dec 13 Python
python3实现将json对象存入Redis以及数据的导入导出
Jul 16 Python
Python Matplotlib简易教程(小白教程)
Jul 28 Python
如何用Matlab和Python读取Netcdf文件
Feb 19 Python
matplotlib 范围选区(SpanSelector)的使用
Feb 24 Python
python实现股票历史数据可视化分析案例
Jun 10 Python
Python中的类与对象之描述符详解
Mar 27 #Python
深入理解Javascript中的this关键字
Mar 27 #Python
Python运用于数据分析的简单教程
Mar 27 #Python
Python中下划线的使用方法
Mar 27 #Python
利用Python和OpenCV库将URL转换为OpenCV格式的方法
Mar 27 #Python
python根据出生年份简单计算生肖的方法
Mar 27 #Python
python实现根据月份和日期得到星座的方法
Mar 27 #Python
You might like
PHP mkdir()定义和用法
2009/01/14 PHP
谨慎使用PHP的引用原因分析
2012/09/06 PHP
使用PHP+Redis实现延迟任务,实现自动取消订单功能
2019/11/21 PHP
yii2.0框架数据库操作简单示例【添加,修改,删除,查询,打印等】
2020/04/13 PHP
关于jQuery UI 使用心得及技巧
2012/10/10 Javascript
JS 去前后空格大全(IE9亲测)
2013/07/15 Javascript
Flexigrid在IE下不显示数据的有效处理方法
2014/09/04 Javascript
JS控制网页动态生成任意行列数表格的方法
2015/03/09 Javascript
JavaScript数组前面插入元素的方法
2015/04/06 Javascript
js如何判断访问是来自搜索引擎(蜘蛛人)还是直接访问
2015/09/14 Javascript
json格式数据的添加,删除及排序方法
2016/01/21 Javascript
JavaScript实现仿淘宝商品购买数量的增减效果
2016/01/22 Javascript
js如何准确获取当前页面url网址信息
2020/09/13 Javascript
javascript类型系统_正则表达式RegExp类型详解
2016/06/24 Javascript
全面总结Javascript对数组对象的各种操作
2017/01/22 Javascript
基于 Vue.js 之 iView UI 框架非工程化实践记录(推荐)
2017/11/21 Javascript
ElementUI Tag组件实现多标签生成的方法示例
2019/07/08 Javascript
Cordova(ionic)项目实现双击返回键退出应用
2019/09/17 Javascript
JavaScript如何处理移动端拍摄图片旋转问题
2019/11/16 Javascript
JS实现滑动拼图验证功能完整示例
2020/03/29 Javascript
Vue自动构建发布脚本的方法示例
2020/07/24 Javascript
[00:43]拉比克至宝魔导师密钥展示
2018/12/20 DOTA
python中base64加密解密方法实例分析
2015/05/16 Python
python处理二进制数据的方法
2015/06/03 Python
Python正则表达式经典入门教程
2017/05/22 Python
Python高级编程之继承问题详解(super与mro)
2019/11/19 Python
Tensorflow读取并输出已保存模型的权重数值方式
2020/01/04 Python
Python实现Word表格转成Excel表格的示例代码
2020/04/16 Python
python3代码输出嵌套式对象实例详解
2020/12/03 Python
Python 实现二叉查找树的示例代码
2020/12/21 Python
深圳-东方伟业笔试部分
2015/02/11 面试题
群众路线查摆问题及整改措施
2014/10/10 职场文书
5.12护士节活动总结
2015/02/10 职场文书
周一问候语大全
2015/11/10 职场文书
CSS3实现的3D隧道效果
2021/04/27 HTML / CSS
JavaScript canvas实现流星特效
2021/05/20 Javascript