python核心编程2 第十四章 练习
2024-09-08 10:06:14
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')
最新文章
- ansible使用文档
- NMAKE:fatal error U1077.“\..\.cl.exe” return code 0xc0000135
- LotusPhp中配置文件组件LtConfig详解
- HW4.36
- php 生成mysql数据字典代码
- hdu4135Co-prime 容斥原理水题
- 8086cpu
- 如何解决java文件上面有错,但是文件夹上面不显示的错误
- js如何获取地址栏的参数
- Open source operational tools
- Hibernate(十二):HQL查询(一)
- 12.22 大湾区.NET Meet 大会
- 【springboot】之自动配置原理
- redcontrol for SL 中文化及样式选择
- 【APP测试(Android)】--交叉事件
- angular的常见问题
- 在Docker容器中运行Spring Boot的jar包 jar外的配置文件无法生效
- IDEA使用笔记(三)——小齿轮的显示和隐藏(Autoscroll from Source)
- RabbitMQ入门_14_Policies
- 【error】no type named ‘type’ in ‘class std::result_of<;void