1:mod:`pty` --- Pseudo-terminal utilities
2========================================
3
4.. module:: pty
5   :platform: Linux
6   :synopsis: Pseudo-Terminal Handling for Linux.
7
8.. moduleauthor:: Steen Lumholt
9.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
10
11**Source code:** :source:`Lib/pty.py`
12
13--------------
14
15The :mod:`pty` module defines operations for handling the pseudo-terminal
16concept: starting another process and being able to write to and read from its
17controlling terminal programmatically.
18
19Because pseudo-terminal handling is highly platform dependent, there is code to
20do it only for Linux. (The Linux code is supposed to work on other platforms,
21but hasn't been tested yet.)
22
23The :mod:`pty` module defines the following functions:
24
25
26.. function:: fork()
27
28   Fork. Connect the child's controlling terminal to a pseudo-terminal. Return
29   value is ``(pid, fd)``. Note that the child  gets *pid* 0, and the *fd* is
30   *invalid*. The parent's return value is the *pid* of the child, and *fd* is a
31   file descriptor connected to the child's controlling terminal (and also to the
32   child's standard input and output).
33
34
35.. function:: openpty()
36
37   Open a new pseudo-terminal pair, using :func:`os.openpty` if possible, or
38   emulation code for generic Unix systems. Return a pair of file descriptors
39   ``(master, slave)``, for the master and the slave end, respectively.
40
41
42.. function:: spawn(argv[, master_read[, stdin_read]])
43
44   Spawn a process, and connect its controlling terminal with the current
45   process's standard io. This is often used to baffle programs which insist on
46   reading from the controlling terminal. It is expected that the process
47   spawned behind the pty will eventually terminate, and when it does *spawn*
48   will return.
49
50   The functions *master_read* and *stdin_read* are passed a file descriptor
51   which they should read from, and they should always return a byte string. In
52   order to force spawn to return before the child process exits an
53   :exc:`OSError` should be thrown.
54
55   The default implementation for both functions will read and return up to 1024
56   bytes each time the function is called. The *master_read* callback is passed
57   the pseudoterminal’s master file descriptor to read output from the child
58   process, and *stdin_read* is passed file descriptor 0, to read from the
59   parent process's standard input.
60
61   Returning an empty byte string from either callback is interpreted as an
62   end-of-file (EOF) condition, and that callback will not be called after
63   that. If *stdin_read* signals EOF the controlling terminal can no longer
64   communicate with the parent process OR the child process. Unless the child
65   process will quit without any input, *spawn* will then loop forever. If
66   *master_read* signals EOF the same behavior results (on linux at least).
67
68   If both callbacks signal EOF then *spawn* will probably never return, unless
69   *select* throws an error on your platform when passed three empty lists. This
70   is a bug, documented in `issue 26228 <https://bugs.python.org/issue26228>`_.
71
72   .. audit-event:: pty.spawn argv pty.spawn
73
74   .. versionchanged:: 3.4
75      :func:`spawn` now returns the status value from :func:`os.waitpid`
76      on the child process.
77
78Example
79-------
80
81.. sectionauthor:: Steen Lumholt
82
83The following program acts like the Unix command :manpage:`script(1)`, using a
84pseudo-terminal to record all input and output of a terminal session in a
85"typescript". ::
86
87    import argparse
88    import os
89    import pty
90    import sys
91    import time
92
93    parser = argparse.ArgumentParser()
94    parser.add_argument('-a', dest='append', action='store_true')
95    parser.add_argument('-p', dest='use_python', action='store_true')
96    parser.add_argument('filename', nargs='?', default='typescript')
97    options = parser.parse_args()
98
99    shell = sys.executable if options.use_python else os.environ.get('SHELL', 'sh')
100    filename = options.filename
101    mode = 'ab' if options.append else 'wb'
102
103    with open(filename, mode) as script:
104        def read(fd):
105            data = os.read(fd, 1024)
106            script.write(data)
107            return data
108
109        print('Script started, file is', filename)
110        script.write(('Script started on %s\n' % time.asctime()).encode())
111
112        pty.spawn(shell, read)
113
114        script.write(('Script done on %s\n' % time.asctime()).encode())
115        print('Script done, file is', filename)
116