热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

《Python核心编程》第14章习题

14-3.执行环境。创建运行其他Python脚本的脚本。filenamerD:\test.pyexecfile(filename)14-4.os.system()。调用o

14-3.执行环境。创建运行其他Python脚本的脚本。

filename = r'D:\test.py'
execfile(filename)
14-4. os.system()。调用os.system()运行程序。附加题:将你的解决方案移植到subprocess.call()。

import os
from subprocess import call

os.system('notepad')
call('notepad')
14-5. commands.getoutput()。用commands.getoutput()解决前面的问题。
from commands import getoutput    output = getoutput('ls')  print output
14-6.popen()家族。选择熟悉的系统命令,该命令从标准输入获得文本,操作或输出数据。使用os.popen()与程序进行通信。
import osdirOut = os.popen('dir')sortIn,sortOut = os.popen2('sort')filenames = dirOut.read()print filenamessortIn.write(filenames)dirOut.close()sortIn.close()print sortOut.read()sortOut.close()
14-7.subprocess模块。把先前问题的解决方案移植到subprocess模块。
from subprocess import Popen,PIPEimport osdirOut = Popen('dir',stdout=PIPE,shell=True).stdoutp = Popen('sort',stdin=PIPE,stdout=PIPE,shell=True)filenames = dirOut.read()print filenamesdirOut.close()p.stdin.write(filenames)p.stdin.close()print p.stdout.read()p.stdout.close()
14-8.exit函数。设计一个在程序退出时的函数,安装到sys.exitfunc(),运行程序,演示你的exit函数确实被调用了。
import sys    def my_exit_func():      print 'show message'    sys.exitfunc = my_exit_func  def usage():    print 'At least 2 args required'    print 'Usage: test.py arg1 arg2'    sys.exit(1)argc = len(sys.argv)if argc <3:    usage()print 'number of args entered:', argcprint 'args were:', sys.argv
14-9.Shells.创建shell ( 操作系统接口)程序。给出接受操作系统命令的命令行接口(任意平台)。
import oswhile 1:    cmd = raw_input('#: ')    if cmd == 'exit':        break    else:        output = os.popen(cmd).readlines()        for out in output:            print out,
14-11.生成和执行python代码。用funcAttrs.py脚本(例14.2)加入测试代码到已有程序的函数中。创建一个测试框架,每次遇到你特殊的函数属性,它都会运行你的测试代码

x = -1
def foo(x):
if x > 0:
return True
else:
return False

foo.tester = '''
if foo(x):
print 'PASSED'
else:
print 'FAILED'
'''

if hasattr(foo,'tester'):
print 'Function "foo(x)" has a tester ... executing'
exec foo.tester
else:
print 'Function "foo(x)" has no tester ... skipping'











推荐阅读
author-avatar
辽河儿女
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有