cpython: e656bece13fa (original) (raw)
Mercurial > cpython
changeset 95981:e656bece13fa 3.4
Issue #23983: Update the pty module example. Changes: * Fixed a ResourceWarning warning * Used argparse instead of getopt [#23983]
Berker Peksag berker.peksag@gmail.com | |
---|---|
date | Tue, 12 May 2015 17:25:06 +0300 |
parents | 7d722c9049ff |
children | 0be7c8f46378 ee7d2c9c70ab |
files | Doc/library/pty.rst |
diffstat | 1 files changed, 24 insertions(+), 32 deletions(-)[+] [-] Doc/library/pty.rst 56 |
line wrap: on
line diff
--- a/Doc/library/pty.rst +++ b/Doc/library/pty.rst @@ -58,40 +58,32 @@ The following program acts like the Unix pseudo-terminal to record all input and output of a terminal session in a "typescript". ::
- mode = 'wb'
- shell = 'sh'
- filename = 'typescript'
- if 'SHELL' in os.environ:
shell = os.environ['SHELL'][](#l1.19)
- try:
opts, args = getopt.getopt(sys.argv[1:], 'ap')[](#l1.22)
- except getopt.error as msg:
print('%s: %s' % (sys.argv[0], msg))[](#l1.24)
sys.exit(2)[](#l1.25)
- parser = argparse.ArgumentParser()
- parser.add_argument('-a', dest='append', action='store_true')
- parser.add_argument('-p', dest='use_python', action='store_true')
- parser.add_argument('filename', nargs='?', default='typescript')
- options = parser.parse_args()
- for opt, arg in opts:
# option -a: append to typescript file[](#l1.33)
if opt == '-a':[](#l1.34)
mode = 'ab'[](#l1.35)
# option -p: use a Python shell as the terminal command[](#l1.36)
elif opt == '-p':[](#l1.37)
shell = sys.executable[](#l1.38)
- if args:
filename = args[0][](#l1.40)
- shell = sys.executable if options.use_python else os.environ.get('SHELL', 'sh')
- filename = options.filename
- mode = 'ab' if options.append else 'wb'
- with open(filename, mode) as script:
def read(fd):[](#l1.47)
data = os.read(fd, 1024)[](#l1.48)
script.write(data)[](#l1.49)
return data[](#l1.50)
print('Script started, file is', filename)[](#l1.56)
script.write(('Script started on %s\n' % time.asctime()).encode())[](#l1.57)
- sys.stdout.write('Script started, file is %s\n' % filename)
- script.write(('Script started on %s\n' % time.asctime()).encode())
- pty.spawn(shell, read)
- script.write(('Script done on %s\n' % time.asctime()).encode())
- sys.stdout.write('Script done, file is %s\n' % filename)
pty.spawn(shell, read)[](#l1.64)
script.write(('Script done on %s\n' % time.asctime()).encode())[](#l1.66)
print('Script done, file is', filename)[](#l1.67)