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.iyunv.com/370259/126831
14-7.
subprocess模块。把先前问题的解决方案移植到subprocess模块。
【答案】
>>> import subprocess
>>> k = subprocess.call('dir', shell = True)
#这里会输出命令dir的结果。
>>> k
0 #这表示命令正确执行了
14-8.
exit函数。设计一个在程序退出时的函数。安装到sys.exitfunc(),运行程序,演示你的exit函数确实被调用了。
【注】
这里附一个英文版书中的原题。
【答案】
代码如下:
import sys
def my_exit():
print 'World'
sys.exitfunc = my_exit
print 'Hello'
sys.exit(1)
print 'there'
运维网声明
1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网 享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com