当前位置: 移动技术网 > IT编程>脚本编程>Python > python核心编程2 第十四章 练习

python核心编程2 第十四章 练习

2019年03月15日  | 移动技术网IT编程  | 我要评论

百兽王战士,二儿子周涵,浴室装修图片

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

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

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

1 import os
2 from subprocess import call
3 
4 if __name__ == '__main__':
5     os.system('ls')
6     call('ls', shell=true)

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

1 from subprocess import getoutput
2 
3 if __name__ == '__main__':
4 
5     output = getoutput('dir')
6     print(output)

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

1 import os
2 
3 if __name__ == '__main__':
4     output = os.popen('dir').readlines()
5     for out in output:
6         print(out, end='')

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

1 from subprocess import popen, pipe
2 
3 if __name__ == '__main__':
4     f = popen('dir', shell=true, stdout=pipe).stdout
5     for line in f:
6         print(line, end='')

14-8.exit函数。设计一个在程序退出时的函数,安装到sys.exitfunc(),运行程序,演示你的exit函数确实被调用了。

 1 import sys
 2 
 3 def my_exit_func():
 4     print('show message')
 5 
 6 sys.exitfunc = my_exit_func
 7 
 8 def usage():
 9     print('at least 2 args required')
10     print('usage: test.py arg1 arg2')
11     sys.exit(1)
12 
13 argc = len(sys.argv)
14 if argc < 3:
15     usage()
16 print('number of args entered:', argc)
17 print('args were:', sys.argv)

 14-9.shells.创建shell(操作系统接口)程序。给出接受操作系统命令的命令行接口(任意平台)。

 1 import os
 2 
 3 while true:
 4     cmd = input('#: ')
 5     if cmd == 'exit':
 6         break
 7     else:
 8         output = os.popen(cmd).readlines()
 9         for out in output:
10             print(out, end='')

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

 1 x = 3
 2 def foo(x):
 3     if x > 0:
 4         return true
 5     return false
 6 
 7 foo.tester = '''
 8 if foo(x):
 9     print('passed')
10 else:
11     print('failed')
12 '''
13 
14 if hasattr(foo, 'tester'):
15     print('function "foo(x)" has a tester... executing')
16     exec(foo.tester)
17 else:
18     print('function "foo(x)" has no tester... skipping')

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网