Chapter 14 exercise of python core programming 2

14-3. Execution environment. Create scripts to run other Python scripts.

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

 14-4. os.system(). Call OS. System() to run the program. Additional question: migrate your solution to 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(). Use commands. Getoutput () to solve the previous problem.

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

14-6.popen() family. Select a familiar system command that takes text, operations, or output data from standard input. Use os.popen() to communicate with the program.

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 module. Migrate the solution of the previous problem to the subprocess module.

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 function. Design a function when the program exits, install it in sys. Exitfunction(), run the program, and show that your exit function is indeed called.

 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. Create a shell (operating system interface) program. Give the command line interface (any platform) to accept the command of the operating system.

 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. Generate and execute python code. Use the funcAttrs.py script (example 14.2) to add the test code to the function of the existing program. Create a test framework that will run your test code every time you encounter special function properties.

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

Keywords: Python shell

Added by jk11uk on Mon, 09 Dec 2019 10:18:01 +0200