Python 基礎實戰(zhàn)
1. 概述
本節(jié)實現(xiàn)一個文件管理程序,該程序會使用到如下知識點:
- 函數(shù)
- 面向?qū)ο?
- 采用面向?qū)ο蟮某绦蛟O計方法對數(shù)據(jù)建模
- 異常處理
- 使用異常處理和文件相關(guān)的錯誤,例如文件不存在
- 模塊
- 程序由多個源文件構(gòu)成,每個源文件實現(xiàn)一個功能模塊
- os 模塊
- 需要使用 os 模塊提供的方法
- sys 模塊
- 需要使用 os 模塊提供的方法
- 文件訪問
2. 程序功能
2.1 概述
文件管理程序提供了如下功能:
- 列出目錄下的文件名
- 打印文件內(nèi)容
- 復制文件
- 刪除文件
文件管理程序是一個命令行程序,讀取用戶輸入命令,然后執(zhí)行返回命令執(zhí)行結(jié)果。文件管理程序支持如下命令:
命令 | 功能 |
---|---|
ls dir | 列出目錄 dir 下的文件 |
cat file | 打印文件 file 的內(nèi)容 |
cp src dst | 復制源文件 src 到目標文件 dst |
rm file | 刪除文件 file |
exit | 退出程序 |
2.2 測試文件 test.txt
本節(jié)需要使用一個用于測試的文本文件 test.txt,內(nèi)容如下:
www
imooc
com
2.3 示例
下面的命令演示了文件管理程序的用法:
2.3.1 啟動程序
C:\> python main.py
>
- 在第 1 行,程序的主文件是
main.py
,啟動程序 - 在第 2 行,程序啟動后,打印提示符 >,等待用戶輸入命令
2.3.2 輸入命令 help
> help
exit - exit program
cat file - print file
ls - list file in current dir
ls dir - list file in dir
cp src dst - copy file
rm file - remove file
- 在第 1 行,輸入命令 help,功能是打印各個命令的用法
2.3.3 輸入命令 cat
> cat test.txt
www
imooc
com
- 在第 1 行,輸入命令 cat test.txt,功能是打印文件 test.txt 的內(nèi)容
2.3.4 輸入命令 ls
> ls
main.py
test.txt
- 在第 1 行,輸入命令 ls,功能是列出當前目錄下的文件
> ls C:\
Documents and Settings
Program Files
Program Files (x86)
ProgramData
System Volume Information
Users
Windows
- 在第 1 行,輸入命令 ls C:\,功能是列出 C 盤根目錄下的文件
2.3.5 輸入命令 cp
> cp test.txt test.bak
> ls
main.py
test.txt
test.bak
- 在第 1 行,輸入命令 cp test.txt test.bak,功能是將文件 test.txt 復制到 test.bak
- 在第 2 行,輸入命令 ls,列出當前目錄下的文件,發(fā)現(xiàn)新增了一個文件 test.bak
2.3.6 輸入命令 rm
> rm test.bak
> ls
main.py
test.txt
- 在第 1 行,輸入命令 rm test.bak,功能是刪除文件 test.bak
- 在第 2 行,輸入命令 ls,列出當前目錄下的文件,發(fā)現(xiàn)文件 test.bak 被刪除了
2.3.6 輸入命令 exit
> exit
C:\>
- 在第 1 行,輸入命令 exit,功能是退出程序
- 在第 2 行,返回到 DOS 命令行模式
2.4 錯誤處理
文件管理程序提供了錯誤處理功能,如果執(zhí)行某條命令時發(fā)生了錯誤,例如文件不存在,僅僅終止該命令,而不是終止程序。
> cat non-exist-file
[Errno 2] No such file or directory: 'non-exisit-file'
>
- 在第 1 行,打印文件 non-exist-file,該文件并不存在,cat 命令運行會出錯
- 在第 2 行,cat 命令執(zhí)行中止,打印錯誤提示信息
- 在第 3 行,cat 命令中止后,打印命令提示符,等待用戶輸入新的命令
3. 程序框架
文件管理程序由多個源文件構(gòu)成,它們的功能如下:
源文件 | 功能 |
---|---|
main.py |
主控程序,讀取用戶的命令并執(zhí)行 |
command.py |
定義類 Command,定義了命令的接口 |
help.py |
定義類 HelpCommand,實現(xiàn) help 命令的功能 |
ls.py |
定義類 LsCommand,實現(xiàn) ls 命令的功能 |
cat.py |
定義類 CatCommand,實現(xiàn) cat 命令的功能 |
cp.py |
定義類 CpCommand,實現(xiàn) cp 命令的功能 |
rm.py |
定義類 RmCommand,實現(xiàn) rm 命令的功能 |
4. 實現(xiàn)主控程序
編寫文件 main.py,讀取用戶的命令并執(zhí)行:
import sys
import cat
import ls
import cp
import rm
import help
- 在第 1 行導入 Python 內(nèi)置的 sys 模塊
- 在第 2 行到第 6 行導入用戶自定義的 5 個模塊
- cat 模塊中定義了類 CatCommand,實現(xiàn) cat 命令的功能
- ls 模塊中定義了類 LsCommand,實現(xiàn) ls 命令的功能
- cp 模塊中定義了類 CpCommand,實現(xiàn) cp 命令的功能
- rm 模塊中定義了類 RmCommand,實現(xiàn) rm 命令的功能
- help 模塊中定義了類 HelpCommand,實現(xiàn) help 命令的功能
def readAndExecute():
print('> ', end = '')
line = input()
args = line.split()
if len(args) == 0:
return
- 在第 1 行,定義函數(shù) readAndExecute(), 讀取用戶輸入的命令并執(zhí)行
- 在第 2 行,打印提示符 >
- 在第 3 行,讀取用戶輸入的命令
- 在第 4 行,將用戶輸入的命令分割為多個單詞
- 假設用戶輸入命令是 cp test.txt test.bak
- 經(jīng)過 split() 后,args = [‘cp’, ‘test.txt’, ‘test.bak’]
arg0 = args[0]
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()
- 第 0 個參數(shù)是命令的名稱,根據(jù)命令的名稱構(gòu)造相應的命令對象
- 如果命令是 exit,調(diào)用 sys 模塊的 exit 方法退出程序
- 如果命令是 cat,使用 cat 模塊中定義的類 CatCommand 實例化一個命令對象
- 如果命令是 ls,使用 ls 模塊中定義的類 LsCommand 實例化一個命令對象
- 如果命令是 cp,使用 cp 模塊中定義的類 CpCommand 實例化一個命令對象
- 如果命令是 rm,使用 rm 模塊中定義的類 RmCommand 實例化一個命令對象
- 如果不是以上命令,使用 help 模塊中定義的類 HelpCommand 實例化一個命令對象
- 在最后,調(diào)用命令對象 command 的 execute 方法執(zhí)行命令
while True:
try:
readAndExecute()
except IOError as error:
print(error)
- 在第 1 行,定義循環(huán),循環(huán)反復執(zhí)行函數(shù) readAndExecute()
- 執(zhí)行函數(shù) readAndExecute 時,可能會出現(xiàn) IOError
- 在 try 語句中執(zhí)行 readAndExecute
- 使用 except 語句捕獲執(zhí)行過程中的 IOError,并打印 error
- 注意,當 readAndExecute 出現(xiàn)異常時,僅僅終止 readAndExecute,而不是終止程序
5. 實現(xiàn)命令接口
編寫文件 command.py
實現(xiàn)命令的接口:
class Command:
def __init__(self, args):
self.args = args
def execute(self):
print('Command.execute')
- 在第 1 行,定義類 Command,描述了一個命令的接口
- __init__ 方法,使用參數(shù)數(shù)組 args 構(gòu)造一個命令
- execute 方法,執(zhí)行命令的功能,這里只提供了一個接口
- 具體的命令如 LsCommand 繼承類 Command,實現(xiàn) execute 方法
6. 實現(xiàn) help 命令
編寫文件 help.py
實現(xiàn) help 命令:
from command import Command
class 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
- 在第 5 行,調(diào)用父類的構(gòu)造函數(shù)
- 在第 7 行,定義 execute 方法,打印各個命令的功能
7. 實現(xiàn) ls 命令
編寫文件ls.py
實現(xiàn) ls 命令:
from command import Command
import os
class 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
- 在第 5 行,調(diào)用父類的構(gòu)造函數(shù)
- 在第 7 行,定義方法 usage 打印 ls 命令的功能
def execute(self):
if len(self.args) == 1:
path = '.'
elif len(self.args) == 2:
path = self.args[1]
else:
self.usage()
return
- 如果執(zhí)行的命令是 ls,則設置 path 為 ‘.’,列出當前目錄下的文件
- 如果執(zhí)行的命令是 ls dir,則設置 path 為 args[1],列出指定目錄下的文件
entries = os.listdir(path)
for entry in entries:
print(entry)
- 調(diào)用 os 模塊的 listdir 方法,列出目錄 path 下的文件
8. 實現(xiàn) cat 命令
編寫文件 cat.py
,定義類 CatCommand 用于實現(xiàn) cat 命令的功能:
from command import Command
class CatCommand(Command):
def __init__(self, args):
Command.__init__(self, args)
def usage(self):
print('cat file - print file')
- 在第 1 行,從 command 模塊中導入類 Command
- 在第 3 行,定義類 HelpCommand,繼承于類 Command
- 在第 5 行,調(diào)用父類的構(gòu)造函數(shù)
- 在第 7 行,定義方法 usage 打印 cat 命令的功能
def execute(self):
if len(self.args) != 2:
self.usage()
return
path = self.args[1]
- 如果命令為 cat file,則設置 path 為 args[1]
file = open(path)
for line in file:
print(line, end = '')
file.close()
- 使用 for 循環(huán)遍歷文件的每一行,并輸出
9. 實現(xiàn) cp 命令
編寫文件 cp.py
,定義類 CpCommand 用于實現(xiàn) cp 命令的功能
from command import Command
class 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
- 在第 5 行,調(diào)用父類的構(gòu)造函數(shù)
- 在第 7 行,定義方法 usage 打印 cp 命令的功能
def execute(self):
if len(self.args) != 3:
self.usage()
return
src_path = self.args[1]
dst_path = self.args[2]
- 設置 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. 實現(xiàn) rm 命令
編寫文件 rm.py
,定義類 RmCommand 用于實現(xiàn) rm 命令的功能
from command import Command
import os
class RmCommand(Command):
def __init__(self, args):
Command.__init__(self, args)
def usage(self):
print('rm file - remove file')
- 在第 1 行,從 command 模塊中導入類 Command
- 在第 3 行,定義類 RmCommand,繼承于類 Command
- 在第 5 行,調(diào)用父類的構(gòu)造函數(shù)
- 在第 7 行,定義方法 usage 打印 rm 命令的功能
def execute(self):
if len(self.args) != 2:
self.usage()
return
path = self.args[1]
os.remove(path)
- 調(diào)用 os 模塊的 remove 方法刪除文件