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')

最新文章

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

热门文章

  1. re模块——正则表达式操作
  2. Microsoft BI - SSRS
  3. 面向对象设计中private,public,protected的访问控制原则及静态代码块的初始化顺序
  4. Azure进阶攻略丨共享访问签名是个什么东东?
  5. Hadoop -&gt;&gt; HIVE
  6. redis 笔记(二)
  7. FileHelpers 用法 z
  8. Python模块 Socket
  9. 关于java文件名字影响系统配置
  10. Android(java)学习笔记43:Map集合的遍历之键找值