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'