python核心编程v2.0 第14章习题答案

part1基础部分到这章就完结了。part2的习题不计划做了。
1.python有4种可调用对象:函数,方法,类以及一些类的实例
eval()语句对表达式求值,表达式可为字符串或内建函数compile()创建的预编译代码对象。
exec()语句执行代码对象或字符串形式的python代码。被执行的对象只可以是原始的字符串或文件对象

2.input()是eval()与raw_input()的结合,等价于eval(raw_input())。raw_input()接收用户输入,返回字符串。input执行相同任务,并将输入以表达式的形式进行求值。返回一个python对象

3.

if __name__ =='__main__':
    execfile('file_test.py')

4.

import os
from subprocess import call

if __name__ =='__main__':
    result = os.system('dir')
    res = call(('dir'),shell=True)

5.
打印出来是乱码

from commands import getoutput
# from commands import getstatusoutput

if __name__ =='__main__':
    res = getoutput('dir')
    print res

6.
popen2()函数返回一个tuple,一个是写模式的文件一个是读模式的文件

import os

if __name__ =='__main__':
    f = os.popen('dir')
    data = f.readlines()
    f.close()
    print data

    f = os.popen2('dir')
    data = f[1].readlines()
    print data

7.
不做stdout = PIPE也会打印出结果,但是会报一个Popen类型没有readlines的错误。

from subprocess import Popen,PIPE

if __name__ =='__main__':
    f = Popen('dir',shell=True,stdout=PIPE).stdout
    data = f.readlines()
    f.close()
    print data

8.

# -*- coding: utf-8 -*-
import sys

prev_exit_func = getattr(sys, 'exitfunc', None)

def my_exit_func(old_exit = prev_exit_func):
    print 'my exit'
    if old_exit is not  None and callable(old_exit):
        old_exit()

sys.exitfunc = my_exit_func
if __name__ =='__main__':
    print 'start'

9.
对shell命令不熟,没有详细写。
大概是需要对命令进行处理,然后用subprocess或其他函数来进行调用

from subprocess import Popen ,PIPE

if __name__ =='__main__':
    while True:
        order = raw_input('order:')
        f = Popen(order,shell=True,stdout=PIPE).stdout
        for i in f:
            print i

10.
spawn家族函数不需要分别调用两个函数来创建进程,并让这个进程执行命令。只需要调用一次,但是无法跟踪父进程和子进程的执行。快于fork()
11.
函数tester属性里面可以定义测试

# -*- coding: utf-8 -*-

def fun():
    print 'a'


fun.tester = '''
print 'b'
'''

if __name__ =='__main__':


    if hasattr(fun, 'tester'):
        print 'Function "foo(x)" has a tester ... executing'
        exec fun.tester
    else:
        print 'Function "foo(x)" has no tester ... skipping'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值