Python笔记(7)
一个Python脚本的开发全过程
问题:完成一个可以为我们所有的重要程序做备份的程序。
步骤拆解:
需要备份的文件和目录由一个列表指定。
文件备份成一个zip文件。
zip存档的名称是当前的日期和时间。
我们使用标准的zip命令,它通常默认地随Linux/Unix发行版提供。Windows用户可以使用Info-Zip程序。注意你可以使用任何地存档命令,只要它有命令行界面就可以了,那样的话我们可以从我们的脚本中传递参数给它。
备份应该保存在主备份目录中。
#!/usr/bin/python
# Filename: backup_ver1.py
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = ['/home/swaroop/byte', '/home/swaroop/bin']
# If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that
# 2. The backup must be stored in a main backup directory
target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using
# 3. The files are backed up into a zip file.
# 4. The name of the zip archive is the current date and time
target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'
# 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup FAILED'
输出为:
$ python backup_ver1.py
Successful backup to /mnt/e/backup/20041208073244.zip
相关文档:
ZoundryDocument
Python skin is known for its color variations and for its elasticity; it is
the warmest leather of the season and ideal for the manufacture of many luxury
goods. Sometimes natural patterns can be hidden when they're done in black, but
the finish here has a bit of a shine to it ......
代码中采用了三步实现算术表达式的解析:
1. 将算术表达式(字符串)转换成一个列表parseElement方法
2. 将列表表示的算术表达式转换成后缀表达式changeToSuffix
3. 计算后缀表达式的结果
这里我是为了方便, 就写了个parseElement, 不想那方法写到后面却把自己绕住了, 可以想象一个带自增, 位, 逻辑, 算术的表达式的数值提 ......
昨天试了下用HTMLParser类来解析网页,可发现结果并不理想。不管怎么说,先写下过程,希望后来人能在此基础上解决我所遇到的问题。
写了2套解决方案,当然这2套只能对特定网站有效。我这里主要说明下对BBC主页www.bbc.co.uk和对网易www.163.com的解析。
对于BBC:
这套要简单得多,可能是该网页的编码比较标准吧
import ......
1. 打印变量和变量自显
>>> myString = 'Hello World!'
>>> print myString
Hello World!
>>> myString
'Hello World!'
因为: print 语句调用str()函数显示对象,而交互式解释器则调用repr()函数来显示对象
sys.stdout.write('hello')不会在末尾加上'\n',而print会
2. 打印文件
hand ......
客户给一堆图片要传到后台,图片太大了,上百张图用photoshop改太慢,就想到用python写个简单的批处理。功能简单就是把原图按比例缩小,代码更简单 20多行。
# -*- coding: cp936 -*-
import Image
import glob, os
#图片批处理
def timage():
for files in glob.glob('D:\\1\\*.JPG'):
filepath,filena ......