zoukankan      html  css  js  c++  java
  • python核心编程2 第十四章 练习

    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')
  • 相关阅读:
    蓝桥杯训练 | 二分和前缀和 | 02
    广西师大数据结构 | 2015年真题 | 02
    广西师大数据结构 | 2014年真题 | 01
    Centos添加开机自启项
    SUSE系统添加开机自启项
    LNMP
    源码编译安装 libiconv-1.14(php依赖)
    lnmp
    centos添加epel源
    系统挂在镜像
  • 原文地址:https://www.cnblogs.com/QQ269075164/p/10523966.html
Copyright © 2011-2022 走看看