这是自己做的练习,可能有错误,欢迎讨论和各种优化重构方案。
根据反馈,或者code review,对本篇文章答案或者相关内容的更新补充,一般会被添加在本篇博客的评论中。
将尽量保证每题的答案代码是完整的,不仅仅是函数,类或者只是个大概,力求打开Python 2.7的IDLE,将代码完整拷贝进去,就能调试运行。
欢迎访问Balian在博客园的家。 http://www.cnblogs.com/balian


14-5.
commands.getoutput()。用commands.getoutput()解决前面的问题。
【答案】
commands.getoutput()在unix平台才能运行。参考http://bugs.python.org/issue15073
曾经尝试在linux的Python 2.5中运行该模块,同样发现语法问题。因为
Deprecated since version 2.6: The commands module has been removed in Python 3. Use the subprocess module instead.


14-6.
popen()家族。选择熟悉的系统命令,该命令从标准输入获得文本,操作或输出数据。(a)使用os.popen()与程序进行通信。输出到哪儿呢?(b)使用popen2.popen2()代替。
【答案】
(a)代码如下:

>>> import os
>>> command = input('Please input a DOS command: ... ')
Please input a DOS command: ... 'dir'

>>> k = os.popen(command)
>>> k
<open file 'dir', mode 'r' at 0x0000000002111420>
>>> print k.read()  #该语句可以读出dir的实际输出

(b)代码如下:

>>> command = 'dir'
>>> import popen2
>>> pipe_in, pipe_out = popen2.popen2(command)
>>> pipe_in.readlines()
#这里会输出命令dir的结果。
>>> pipe_in.close()

【参考】
http://www.360doc.com/content/12/0131/16/2660674_183157204.shtml
http://linhs.blog.51cto.com/370259/126831


14-7.
subprocess模块。把先前问题的解决方案移植到subprocess模块。
【答案】

>>> import subprocess
>>> k = subprocess.call('dir', shell = True)
#这里会输出命令dir的结果。
>>> k
0   #这表示命令正确执行了

 

14-8.
exit函数。设计一个在程序退出时的函数。安装到sys.exitfunc(),运行程序,演示你的exit函数确实被调用了。
【注】
这里附一个英文版书中的原题。

image

【答案】
代码如下:

import sys

def my_exit():
    print 'World'
    
sys.exitfunc = my_exit

print 'Hello'
sys.exit(1)

print 'there'

【参考】
http://effbot.org/librarybook/sys-exitfunc-example-1.py

posted on 2013-03-12 11:52  balian  阅读(571)  评论(0编辑  收藏  举报