python核心编程2 第14章 练习

本文探讨了Python中执行环境的创建与管理,包括通过不同方法调用外部程序,如os.system(), subprocess.call(), commands.getoutput(), os.popen()及subprocess模块。同时,文章还介绍了如何使用exit函数优雅地结束程序,并展示了shell程序的创建,以及如何在Python代码中动态生成和执行测试代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

if __name__ == '__main__':
    with open('test.py') as f:
        exec(f.read())

14-4. os.system()。调用os.system()运行程序。附加题:将你的解决方案移植到subprocess.call()。

import os
from subprocess import call

if __name__ == '__main__':
    os.system('ls')
    call('ls', shell=True)

14-5. commands.getoutput()。用commands.getoutput()解决前面的问题。

from subprocess import getoutput

if __name__ == '__main__':

    output = getoutput('dir')
    print(output)

 14-6.popen()家族。选择熟悉的系统命令,该命令从标准输入获得文本,操作或输出数据。使用os.popen()与程序进行通信。

import os

if __name__ == '__main__':
    output = os.popen('dir').readlines()
    for out in output:
        print(out, end='')

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

from subprocess import Popen, PIPE

if __name__ == '__main__':
    f = Popen('dir', shell=True, stdout=PIPE).stdout
    for line in f:
        print(line, end='')

 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 True:
    cmd = input('#: ')
    if cmd == 'exit':
        break
    else:
        output = os.popen(cmd).readlines()
        for out in output:
            print(out, end='')

14-11.生成和执行python代码。用funcAttrs.py脚本(例14.2)加入测试代码到已有程序的函数中。创建一个测试框架,每次遇到你特殊的函数属性,它都会运行你的测试代码。

x = 3
def foo(x):
    if x > 0:
        return True
    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')

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值