Python 基础实战
1. 概述
2. 程序功能
2.1 概述
文件管理程序是一个命令行程序,读取用户输入命令,然后执行返回命令执行结果。文件管理程序支持如下命令:
命令 | 功能 |
---|---|
ls dir | 列出目录 dir 下的文件 |
cat file | 打印文件 file 的内容 |
cp src dst | 复制源文件 src 到目标文件 dst |
rm file | 删除文件 file |
exit | 退出程序 |
2.2 测试文件 test.txt
本节需要使用一个用于测试的文本文件 test.txt,内容如下:
www imooc com
2.3 示例
2.3.1 启动程序
C:\> python main.py>
2.3.2 输入命令 help
> helpexit - exit programcat file - print filels - list file in current dirls dir - list file in dircp src dst - copy filerm file - remove file
2.3.3 输入命令 cat
> cat test.txt www imooc com
2.3.4 输入命令 ls
> lsmain.py test.txt
> ls C:\ Documents and Settings Program Files Program Files (x86) ProgramData System Volume @R_651_4045@ion Users Windows
2.3.5 输入命令 cp
> cp test.txt test.bak> lsmain.py test.txt test.bak
2.3.6 输入命令 rm
> rm test.bak> lsmain.py test.txt
2.3.6 输入命令 exit
> exitC:\>
2.4 错误处理
文件管理程序提供了错误处理功能,如果执行某条命令时发生了错误,例如文件不存在,仅仅终止该命令,而不是终止程序。
> cat non-exist-file[Errno 2] No such file or directory: 'non-exisit-file'>
3. 程序框架
源文件 | 功能 |
---|---|
main.py | 主控程序,读取用户的命令并执行 |
command.py | 定义类 Command,定义了命令的接口 |
help.py | 定义类 HelpCommand,实现 help 命令的功能 |
ls.py | 定义类 LsCommand,实现 ls 命令的功能 |
cat.py | 定义类 CatCommand,实现 cat 命令的功能 |
cp.py | 定义类 CpCommand,实现 cp 命令的功能 |
rm.py | 定义类 RmCommand,实现 rm 命令的功能 |
4. 实现主控程序
import sysimport catimport lsimport cpimport rmimport help
在第 1 行导入 Python 内置的 sys 模块
def readAndExecute():print('> ', end = '')line = input()args = line.split()if len(args) == :return
在第 2 行,打印提示符 >
在第 3 行,读取用户输入的命令
在第 4 行,将用户输入的命令分割为多个单词
假设用户输入命令是 cp test.txt test.bak
经过 split() 后,args = [‘cp’, ‘test.txt’, ‘test.bak’]
arg0 = args[]if arg0 == 'exit':sys.exit()elif arg0 == 'cat':command = cat.CatCommand(args)elif arg0 == 'ls':command = ls.LsCommand(args)elif arg0 == 'cp':command = cp.CpCommand(args)elif arg0 == 'rm':command = rm.RmCommand(args)else:command = help.HelpCommand(args)command.execute()
如果命令是 cat,使用 cat 模块中定义的类 CatCommand 实例化一个命令对象
如果命令是 ls,使用 ls 模块中定义的类 LsCommand 实例化一个命令对象
如果命令是 cp,使用 cp 模块中定义的类 CpCommand 实例化一个命令对象
如果命令是 rm,使用 rm 模块中定义的类 RmCommand 实例化一个命令对象
如果不是以上命令,使用 help 模块中定义的类 HelpCommand 实例化一个命令对象
while True:try:readAndExecute()except IOError as error:print(error)
在第 1 行,定义循环,循环反复执行函数 readAndExecute()
执行函数 readAndExecute 时,可能会出现 IOError
在 try 语句中执行 readAndExecute
使用 except 语句捕获执行过程中的 IOError,并打印 error
注意,当 readAndExecute 出现异常时,仅仅终止 readAndExecute,而不是终止程序
5. 实现命令接口
编写文件 command.py
实现命令的接口:
class Command:def __init__(self, args):self.args = argsdef execute(self):print('Command.execute')
6. 实现 help 命令
编写文件 help.py
实现 help 命令:
from command import Commandclass HelpCommand(Command):def __init__(self, args):Command.__init__(self, args)def execute(self):print('exit - exit program')print('cat file - print file')print('ls - list file in current dir')print('ls dir - list file in dir')print('cp src dst - copy file')print('rm file - remove file')
在第 1 行,从 command 模块中导入类 Command
在第 3 行,定义类 HelpCommand,继承于类 Command
7. 实现 ls 命令
编写文件ls.py
实现 ls 命令:
from command import Commandimport osclass LsCommand(Command):def __init__(self, args):Command.__init__(self, args)def usage(self):print('ls - list file in current dir')print('ls dir - list file in dir')
在第 1 行,从 command 模块中导入类 Command
在第 3 行,定义类 HelpCommand,继承于类 Command
def execute(self):if len(self.args) == :path = '.'elif len(self.args) == :path = self.args[]else:self.usage()return
entries = os.listdir(path) for entry in entries: print(entry)
8. 实现 cat 命令
编写文件 cat.py
,定义类 CatCommand 用于实现 cat 命令的功能:
from command import Commandclass CatCommand(Command):def __init__(self, args):Command.__init__(self, args)def usage(self):print('cat file - print file')
在第 1 行,从 command 模块中导入类 Command
在第 3 行,定义类 HelpCommand,继承于类 Command
def execute(self):if len(self.args) != :self.usage()returnpath = self.args[]
如果命令为 cat file,则设置 path 为 args[1]
file = open(path)for line in file:print(line, end = '')file.close()
9. 实现 cp 命令
编写文件 cp.py
,定义类 CpCommand 用于实现 cp 命令的功能
from command import Commandclass CpCommand(Command):def __init__(self, args):Command.__init__(self, args)def usage(self):print('cp src dst - copy file')
在第 1 行,从 command 模块中导入类 Command
在第 3 行,定义类 CpCommand,继承于类 Command
def execute(self):if len(self.args) != :self.usage()returnsrc_path = self.args[]dst_path = self.args[]
设置 src_path 为 args[1]
设置 dst_path 为 args[2]
src_file = open(src_path, 'r')dst_file = open(dst_path, 'w')for line in src_file:dst_file.write(line)src_file.close()dst_file.close()
以只读方式打开 src_path,以只写方式打开 dst_path
遍历源文件 src_file 的每一行,将其写入到 dst_file 中
10. 实现 rm 命令
编写文件 rm.py
,定义类 RmCommand 用于实现 rm 命令的功能
from command import Commandimport osclass RmCommand(Command):def __init__(self, args):Command.__init__(self, args)def usage(self):print('rm file - remove file')
在第 1 行,从 command 模块中导入类 Command
在第 3 行,定义类 RmCommand,继承于类 Command
def execute(self):if len(self.args) != :self.usage()returnpath = self.args[]os.remove(path)