Python一个备份程序
这里需要调用rar命令,首先把rar命令加入到环境变量里面来:
我的RAR.exe 在C:\Program Files\WinRAR,加入环境变量后,示例备份程序helloworld.py mymodule.py到myPythonProgram.rar
<span style="font-family:Microsoft YaHei;font-size:14px;">#Backup script
#DOS下解压命令行:rar a myPythonProgram mymodule.py helloworld.py
#导入模块
import os
import time
#源路径
source = [r'.\mymodule.py', r'.\helloworld.py']
#目标路径
targetDir = r'.\myPythonProgram'
#DOS压缩命令
rarCommand = 'rar a %s %s' % (targetDir, ' '.join(source))
#执行DOS命令
if os.system(rarCommand) == 0:
print('Backup successful')
else:
print('failed')
print(rarCommand)</span>
Python面向对象一个程序示例
一个例子代码展示如下:
<span style="font-family:Microsoft YaHei;font-size:14px;">#using class and object
#定义类
class Person:
#类变量population,相当于c++中静态成员变量
population = 0
#init初始化函数 相当于c++构造函数
def __init__(self, name):
#self.name是对象成员
self.name = name
print('initialise %s' % self.name)
Person.population += 1
#del函数 相当于c++析构函数
def __del__(self):
print('%s is dying' % self.name)
if self.__class__.population > 0:
self.__class__.population -= 1
#成员函数
def sayHi(self):
print('hi, my name is %s' % self.name)
#成员函数
def howMany(self):
if Person.population == 1:
print('I am the last person')
else:
print('there are %d person left' % Person.population)
#创造对象
p1 = Person('Tom')
p1.sayHi()
p1.howMany()
p2 = Person('Jack')
p2.sayHi()
p2.howMany()
#result:
# initialise Tom
# hi, my name is Tom
# I am the last person
# initialise Jack
# hi, my name is Jack
# there are 2 person left
# Jack is dying
# Tom is dying</span>
这里需要注意在类的del函数里面,访问类变量(class variable)用self.__class__.来代替,否则可能会报如下错误:
Exception AttributeError: "'NoneType' object has no attribute
python读写文件示例
一个读写文件的示例:
<span style="font-family:Microsoft YaHei;font-size:14px;">#using files
#待写入的文本
text = '''\
I felt very happy.
Today I go out
He is stupid'''
#以写入方式打开文件
f = open('test.txt', 'w') #可以是二进制写'wb'
#写入
f.write(text)
#关闭文件
f.close()
#读文件
f = open('test.txt', 'r') #不写‘r’,默认是只读打开,也可以二进制读'rb'
while True:
line = f.readline()
if len(line) == 0: #为0表示文件结束
break
else:
print(line)
#关闭文件
f.close()
#result:
# I felt very happy.
# Today I go out
# He is stupidV</span>
python自定义异常对象、捕获异常
<span style="font-family:Microsoft YaHei;font-size:14px;">#using exception
#处理异常
try:
text = input('please input something:')
except EOFError:
print('you enter EOF!')
except KeyboardInterrupt:
print('you canceld the operation')
else:
print('you entered %s' % text)
#在windows DOS下结果:
# please input something:^Z
# you enter EOF!
# please input something:you canceld the operation [ctr + c]
# please input something:how are you
# you entered how are you
#自定义异常对象并引发
class MyInputException(Exception):
def __init__(self, length, least):
Exception.__init__(self)
self.length = length
self.least = least
try:
text = input('please input again:')
if len(text) < 4:
raise MyInputException(len(text), 4)
except EOFError:
print('you input EOF!')
except MyInputException as ex:
print('you enter %d , at least %d' % (ex.length, ex.least))
finally:
print('you entered %s' % text)</span>
sys.argv小程序
下面这个例子来自a byte of python是练习sys.argv的<span style="font-family:Microsoft YaHei;font-size:14px;">#using sys.argv
import sys
#读文件函数
def readfiles(filename):
try:
f = open(filename, 'r')
except Exception:
print('%s not exist!' % filename)
return
while True:
line = f.readline()
if len(line) == 0:
break
else:
print(line)
#命令行命令解析
if sys.argv[1].startswith('--'): #解析参数选项
option = sys.argv[1][2:]
if option == 'version':
print('version 1.1')
elif option == 'help':
print('''\
This program prints file to standard
option includes:
--version: print current version
--help: show help''')
else:
print('unknown option')
else: #打印文件
for filename in sys.argv[1:]: #注意这里元组slice的用法 灵活方便</span>