• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`!pty` --- Pseudo-terminal utilities
2=========================================
3
4.. module:: pty
5   :platform: Unix
6   :synopsis: Pseudo-Terminal Handling for Unix.
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
19.. availability:: Unix.
20
21Pseudo-terminal handling is highly platform dependent. This code is mainly
22tested on Linux, FreeBSD, and macOS (it is supposed to work on other POSIX
23platforms but it's not been thoroughly tested).
24
25The :mod:`pty` module defines the following functions:
26
27
28.. function:: fork()
29
30   Fork. Connect the child's controlling terminal to a pseudo-terminal. Return
31   value is ``(pid, fd)``. Note that the child  gets *pid* 0, and the *fd* is
32   *invalid*. The parent's return value is the *pid* of the child, and *fd* is a
33   file descriptor connected to the child's controlling terminal (and also to the
34   child's standard input and output).
35
36   .. warning:: On macOS the use of this function is unsafe when mixed with using
37      higher-level system APIs, and that includes using :mod:`urllib.request`.
38
39
40.. function:: openpty()
41
42   Open a new pseudo-terminal pair, using :func:`os.openpty` if possible, or
43   emulation code for generic Unix systems. Return a pair of file descriptors
44   ``(master, slave)``, for the master and the slave end, respectively.
45
46
47.. function:: spawn(argv[, master_read[, stdin_read]])
48
49   Spawn a process, and connect its controlling terminal with the current
50   process's standard io. This is often used to baffle programs which insist on
51   reading from the controlling terminal. It is expected that the process
52   spawned behind the pty will eventually terminate, and when it does *spawn*
53   will return.
54
55   A loop copies STDIN of the current process to the child and data received
56   from the child to STDOUT of the current process. It is not signaled to the
57   child if STDIN of the current process closes down.
58
59   The functions *master_read* and *stdin_read* are passed a file descriptor
60   which they should read from, and they should always return a byte string. In
61   order to force spawn to return before the child process exits an
62   empty byte array should be returned to signal end of file.
63
64   The default implementation for both functions will read and return up to 1024
65   bytes each time the function is called. The *master_read* callback is passed
66   the pseudoterminal’s master file descriptor to read output from the child
67   process, and *stdin_read* is passed file descriptor 0, to read from the
68   parent process's standard input.
69
70   Returning an empty byte string from either callback is interpreted as an
71   end-of-file (EOF) condition, and that callback will not be called after
72   that. If *stdin_read* signals EOF the controlling terminal can no longer
73   communicate with the parent process OR the child process. Unless the child
74   process will quit without any input, *spawn* will then loop forever. If
75   *master_read* signals EOF the same behavior results (on linux at least).
76
77   Return the exit status value from :func:`os.waitpid` on the child process.
78
79   :func:`os.waitstatus_to_exitcode` can be used to convert the exit status into
80   an exit code.
81
82   .. audit-event:: pty.spawn argv pty.spawn
83
84   .. versionchanged:: 3.4
85      :func:`spawn` now returns the status value from :func:`os.waitpid`
86      on the child process.
87
88Example
89-------
90
91.. sectionauthor:: Steen Lumholt
92
93The following program acts like the Unix command :manpage:`script(1)`, using a
94pseudo-terminal to record all input and output of a terminal session in a
95"typescript". ::
96
97    import argparse
98    import os
99    import pty
100    import sys
101    import time
102
103    parser = argparse.ArgumentParser()
104    parser.add_argument('-a', dest='append', action='store_true')
105    parser.add_argument('-p', dest='use_python', action='store_true')
106    parser.add_argument('filename', nargs='?', default='typescript')
107    options = parser.parse_args()
108
109    shell = sys.executable if options.use_python else os.environ.get('SHELL', 'sh')
110    filename = options.filename
111    mode = 'ab' if options.append else 'wb'
112
113    with open(filename, mode) as script:
114        def read(fd):
115            data = os.read(fd, 1024)
116            script.write(data)
117            return data
118
119        print('Script started, file is', filename)
120        script.write(('Script started on %s\n' % time.asctime()).encode())
121
122        pty.spawn(shell, read)
123
124        script.write(('Script done on %s\n' % time.asctime()).encode())
125        print('Script done, file is', filename)
126