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'