概述:
本程序主要是模仿《Python核心编程》中3.6节——第一个Python程序,并在其基础上做了一些小的改进,而改进的要求则是来源于第三章的课后练习题。
本篇博客的一个核心问题就是在我们如何避免重复制造轮子。
课本源程序:
这里不对课本上的源程序作过多地讲解,因为课本本身就说得非常清楚而且易懂。
改进需求:
1. 可以创建新的文件;
2. 可以读取新的文件;
3. 可以让用户选择创建或是读取文件.
看到上面的需求,可以你的第一感觉就是,哦,这个太简单了。不就是把之前写过的代码在这里复制粘贴一下就好了啊,最多不过是多加一个if的判断,有什么难的?
当然我并不否认,这的确是一个简单的程序。不过从优良的代码质量来看,可不能是简单的复制和粘贴这么简单哦。因为复制代码到自己的程序中,这会导致代码的复用性大幅下降,对于小程序可能是没有什么影响,可是对于一些庞大的系统来说,这可能是一个致命的伤,因为维护起来可能会异常艰难。好了,说了这么多,那就来看看我是怎么解决这个需求的吧。
思路:
我把之前创建文件和读取文件的文件还是保留,然后在第三个文件makeNreadTextFile.py中使用代码去调用前两个文件中的方法。
代码分析:
makeNreadTextFile.py
#!/usr/bin/env python
'makeNreadTextFile.py -- create or read a text file'
import subprocess
# call makeTextFile.py
def call_make():
cmd = [ "python", "makeTextFile.py"]
result = subprocess.call(cmd, 0, None, None, None, None)
return result
# call readTextFile.py
def call_read():
cmd = [ "python", "readTextFile.py"]
result = subprocess.call(cmd, 0, None, None, None, None)
return result
# get the choose to read or make a text file
choose = raw_input('Enter the choose(r/m)')
if choose == 'm':
call_make()
elif choose == 'M':
call_make()
elif choose == 'r':
call_read()
elif choose == 'R':
call_read()
else:
print 'your choose is error!'
大家可以看到上面有几个地方比较特殊:
1.import subprocess
你百度过后就会知道subprocess是开启一个新的线程,并与之通信。
2.result = subprocess.call(cmd, 0, None, None, None, None)
通过1就应该知道,这里就是正在通信。
当然,如果只是对书本上的代码做完整保留,可能达不到我们想要的效果。于是,需要做一些小小的修改。
makeTextFile.py
#!/usr/bin/env python
'makeTextFile.py -- create text file'
import os
ls = os.linesep
def make_text_file():
# get filename
while True:
fname = raw_input('Enter file name:')
if os.path.exists(fname):
print "ERROR: '%s' already exists" % fname
else:
break
# get file content (text) lines
all = []
print "\nEnter lines('.' by iteslf to quit).\n"
#loop until user terminates input
while True:
entry = raw_input('>')
if entry == '.':
break
else:
all.append(entry)
# write lines to file with proper line-ending
fobj = open(fname, 'w')
fobj.writelines(['%s%s' % (x, ls) for x in all])
fobj.close()
print 'DONE!'
if __name__ == "__main__":
make_text_file()
readTextFile.py
#!/usr/bin/env Python
'readTextFile.py -- read and display text file'
def read_text_file():
# get filename
fname = raw_input('Enter filename:')
# attemp to open file for reading
try:
fobj = open(fname, 'r')
except IOError, e:
print "*** file open error:", e
else:
# display contents to the screen
for eachLine in fobj:
print eachLine,
fobj.close()
if __name__ == "__main__":
read_text_file()
运行效果:
注:这里是利用执行其他Python程序的方式来实现复用。不过,如果你已经学习了《Python核心编程》的第13章或是了解了Python中的class的话,你同样可以利用类的面向对象来解决问题。