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

本文探讨了如何创建一个Python脚本,该脚本能够执行并控制其他Python脚本的运行,深入理解Python的执行环境及其应用。
摘要由CSDN通过智能技术生成

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 os

dirOut = os.popen('dir')
sortIn,sortOut = os.popen2('sort')

filenames = dirOut.read()
print filenames

sortIn.write(filenames)
dirOut.close()
sortIn.close()

print sortOut.read()
sortOut.close()
14-7.subprocess模块。把先前问题的解决方案移植到subprocess模块。
from subprocess import Popen,PIPE
import os

dirOut = Popen('dir',stdout=PIPE,shell=True).stdout

p = Popen('sort',stdin=PIPE,stdout=PIPE,shell=True)

filenames = dirOut.read()
print filenames
dirOut.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:', argc
print 'args were:', sys.argv
14-9.Shells.创建shell ( 操作系统接口)程序。给出接受操作系统命令的命令行接口(任意平台)。
import os

while 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'










  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值