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
相关文档:
代码中采用了三步实现算术表达式的解析:
1. 将算术表达式(字符串)转换成一个列表parseElement方法
2. 将列表表示的算术表达式转换成后缀表达式changeToSuffix
3. 计算后缀表达式的结果
这里我是为了方便, 就写了个parseElement, 不想那方法写到后面却把自己绕住了, 可以想象一个带自增, 位, 逻辑, 算术的表达式的数值提 ......
$ 字符串的末尾
^ 字符串的开始
\b 字符的边界
前缀t 字符串中的反斜线(所有字符)不转义
? 可选地匹配(位于之前的)单个字符
() 改变优先级,作为一个整体,一个组
| 或者
(A|B) 精确匹配A或B中的一个
{n,m} 匹配(位于之前的字符)n到m次
VERBOSE ......
偶然需要用到这样一个函数,在Delphi中,有现成的函数可以调用!在python中,我找了半天都还没找到,最后自己写了一个函数如下:
def dayOfMonth(date):
if date.month == 12:
return 31
else:
return (date.replace(month=date.month+1, day=1) - datetime.timedelta(days=1)).day
......
刚刚写完Python嵌入部分的简单例子(差不多够现在用的啦~),接着看点实际的东西,如果没有这些应用的话,前面的嵌入也没有什么意义。嵌入的其他部分以后遇到再写,不必一下子把那些函数都弄懂,是吧~
OK,来看Python库中我认为最好玩的一部分,也就是Python对网页的操作。
这篇简单说下如何通过网址下载网页,前提当然是 ......
Python lists have a built-in sort() method that modifies the list in-place and a sorted() built-in function that builds a new sorted list from an iterable.
There are many ways to use them to sort data and there doesn't appear to be a single, central place in the various man ......