32. Python脚本学习笔记三十二开始编程

本篇名言:“逃避不一定躲得过,面对不一定最难受,孤单不一定不快乐,得到不一定能常久,失去不一定不再有,转身不一定最软弱。”

                  一路学习过来,现在需要来点综合能力提升了。提升完毕后再来点实例操作耍耍。开工走你。

                  Python最有意思的地方是能让工作变得非常富有成就感。不要将没有预料到的事件看做让人沮丧的意外,而要将他们作为探索新的选择和可能性的起点。     

1.  原型设计

原型意味着实验性的实现。

在将一些思想融入到程序的结构中后,建议实现一个简单的版本。

Python的强大之处在于编写一个模型只需要很少的投入,而不用大动干戈。

在原型设计阶段,快速拼凑出一个能解决问题的程序,了解所需要的组件和优秀解决方案的需求。随时看到程序的所有纰漏。

如果原型程序能完善为可以工作的系统,那不管怎么说都要坚持下去,而不是推倒重来。

从头写代码是任何软件公司都会犯下的最糟糕的决策性错误。

2.  配置

为自己使用方便提取常量是一码事,还要考虑有哪些常量是要公开给用户的。如用户不喜欢GUI程序的背景色,那就应该允许他们换另外一种颜色。

编写配置文件如下:

 

[numbers]

pi: 3.1415926535897931

[messages]

greeting: Welcometo the area calculation program!

question: Pleaseenter the radius:

result_message:The area is

 

使用配置文件如下:

fromConfigParser import ConfigParser

 

CONFIGFILE = "python.txt"

 

config = ConfigParser()

# Read the configuration file:

config.read(CONFIGFILE)

 

# Print out an initial greeting;

# 'messages' is the section tolook in:

printconfig.get('messages', 'greeting')

 

# Read in the radius, using aquestion from the config file:

radius = input(config.get('messages', 'question') + ' ')

 

# Print a result message from the configfile;

# end with a comma to stay on sameline:

printconfig.get('messages', 'result_message'),

 

# getfloat() converts the configvalue to a float:

printconfig.getfloat('numbers', 'pi')* radius**2

最后输出结果如下:

Welcometo the area calculation program!

Pleaseenter the radius: 2

The area is12.5663706144

3.  日志记录

日志记录基本上是收集与程序运行有关的数据。可以再随后进行检查。

我们可以使用logging模块。

使用logging模块示例如下:

importlogging

 

logging.basicConfig(level=logging.INFO,filename='mylog.log')

 

logging.info('Starting program')

 

logging.info('Trying to divide 1 by 0')

 

print1 / 0

 

logging.info('The division succeeded')

 

logging.info('Endingprogram')

由于使用分母为0,导致程序出错退出。

然后我们发现在mylog.log文件中,记录了

INFO:root:Starting program

INFO:root:Trying to divide 1 by 0

当然,logging模块非常高级,其他可以查看http://python.org/doc/lib/module-logging.html