termios —- POSIX style tty control
This module provides an interface to the POSIX calls for tty I/O control. For acomplete description of these calls, see termios(3)) Unix manualpage. It is only available for those Unix versions that support POSIXtermios style tty I/O control configured during installation.
All functions in this module take a file descriptor fd as their firstargument. This can be an integer file descriptor, such as returned bysys.stdin.fileno()
, or a file object, such as sys.stdin
itself.
This module also defines all the constants needed to work with the functionsprovided here; these have the same name as their counterparts in C. Pleaserefer to your system documentation for more information on using these terminalcontrol interfaces.
这个模块定义了以下函数:
termios.
tcgetattr
(fd)Return a list containing the tty attributes for file descriptor fd, asfollows:
[iflag, oflag, cflag, lflag, ispeed, ospeed, cc]
where cc is alist of the tty special characters (each a string of length 1, except theitems with indicesVMIN
andVTIME
, which are integers whenthese fields are defined). The interpretation of the flags and the speeds aswell as the indexing in the cc array must be done using the symbolicconstants defined in thetermios
module.Set the tty attributes for file descriptor fd from the attributes, which isa list like the one returned by
tcgetattr()
. The when argumentdetermines when the attributes are changed:TCSANOW
to changeimmediately,TCSADRAIN
to change after transmitting all queued output,orTCSAFLUSH
to change after transmitting all queued output anddiscarding all queued input.Send a break on file descriptor fd. A zero duration sends a break for0.25—0.5 seconds; a nonzero duration has a system dependent meaning.
Wait until all output written to file descriptor fd has been transmitted.
Discard queued data on file descriptor fd. The queue selector specifieswhich queue:
TCIFLUSH
for the input queue,TCOFLUSH
for theoutput queue, orTCIOFLUSH
for both queues.- Suspend or resume input or output on file descriptor fd. The _action_argument can be
TCOOFF
to suspend output,TCOON
to restartoutput,TCIOFF
to suspend input, orTCION
to restart input.
参见
- Module
tty
- Convenience functions for common terminal control operations.
示例
Here's a function that prompts for a password with echoing turned off. Note thetechnique using a separate tcgetattr()
call and a try
…finally
statement to ensure that the old tty attributes are restoredexactly no matter what happens:
- def getpass(prompt="Password: "):
- import termios, sys
- fd = sys.stdin.fileno()
- old = termios.tcgetattr(fd)
- new = termios.tcgetattr(fd)
- new[3] = new[3] & ~termios.ECHO # lflags
- try:
- termios.tcsetattr(fd, termios.TCSADRAIN, new)
- passwd = input(prompt)
- finally:
- termios.tcsetattr(fd, termios.TCSADRAIN, old)
- return passwd