35.6. termios — POSIX 样式 tty 控制

This module provides an interface to the POSIX calls for tty I/O control. For a complete description of these calls, see the POSIX or Unix manual pages. It is only available for those Unix versions that support POSIX termios style tty I/O control (and then only if configured at installation time).

本模块中的所有函数接受文件描述符 fd 作为其第 1 自变量。这可以是整数文件描述符,譬如返回通过 sys.stdin.fileno() ,或 文件对象 ,譬如 sys.stdin 本身。

This module also defines all the constants needed to work with the functions provided here; these have the same name as their counterparts in C. Please refer to your system documentation for more information on using these terminal control interfaces.

模块定义了下列函数:

termios. tcgetattr ( fd )

Return a list containing the tty attributes for file descriptor fd , as follows: [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] where cc is a list of the tty special characters (each a string of length 1, except the items with indices VMIN and VTIME , which are integers when these fields are defined). The interpretation of the flags and the speeds as well as the indexing in the cc array must be done using the symbolic constants defined in the termios 模块。

termios. tcsetattr ( fd , , 属性 )

Set the tty attributes for file descriptor fd 属性 , which is a list like the one returned by tcgetattr() argument determines when the attributes are changed: TCSANOW to change immediately, TCSADRAIN to change after transmitting all queued output, or TCSAFLUSH to change after transmitting all queued output and discarding all queued input.

termios. tcsendbreak ( fd , duration )

Send a break on file descriptor fd . A zero duration sends a break for 0.25 –0.5 seconds; a nonzero duration has a system dependent meaning.

termios. tcdrain ( fd )

Wait until all output written to file descriptor fd has been transmitted.

termios. tcflush ( fd , queue )

Discard queued data on file descriptor fd queue selector specifies which queue: TCIFLUSH for the input queue, TCOFLUSH for the output queue, or TCIOFLUSH for both queues.

termios. tcflow ( fd , action )

挂起 (或再继续) 输入/输出对于文件描述符 fd action 自变量可以是 TCOOFF 以挂起输出, TCOON 以重启输出, TCIOFF 以挂起输入,或 TCION 以重启输入。

另请参阅

模块 tty
用于常用终端控制操作的方便函数。

35.6.1. 范例

Here’s a function that prompts for a password with echoing turned off. Note the technique using a separate tcgetattr() call and a try ... finally statement to ensure that the old tty attributes are restored exactly 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
					

内容表

上一话题

35.5. crypt — 用于校验 Unix 口令的函数

下一话题

35.7. tty — 终端控制函数

本页