Background: In a weekly meeting of the project team, one of the fixed content is technology sharing, which can be any technical topic that is relevant or irrelevant to the job. The students who carry out the technology sharing instruction are randomly drawn by lottery. This makes a small Python script for extracting names.
The script reads as follows:
#!/usr/bin/pythonimport osimport sysimport tty, termiosimport randomname_list = ["member_1", "member_2", "member_3"] input = ' FD = Sys.stdin.fileno () old_settings = termios.tcgetattr (FD) Try: Tty.setraw (FD) while ' q '! = Input: Sys.stdout.write (Random.choice (name_list) + "\ r \ n") input = sys.stdin.read (1) Finally: Termios.tcgetattr (FD, Termios. Tcsadrain, Old_settings)
Code Description:
Random selection
$ random.choice Gets a random element from the sequence.
$ its function prototype is: Random.choice (sequence). The parameter sequence represents an ordered type.
$ sequence in Python is not a specific type, but a series of types. list, tuple, string all belong to sequence.
File descriptor
$ gets the underlying implementation using the request file descriptor from the operating system for I/O operations:
The $ script Gets the file descriptor for the standard input (terminal), which is subsequently used to get input and output to the screen. In fact, reading the standard input, I prefer to use the raw_input () This function, but has been implemented anyway. The reason for the use of Sys.stdout.write () in the input is that after changing the properties of the terminal through Termios, the format will change when using the print output-if you extract multiple times, the name of each output will be in the next row of the previous output and the position of the tab is deferred. Cause dislocation, do not know why. After adopting Sys.stdout.write (), it is normal.
Termios and TTY Modules
$ (only available in UNIX and its derived systems) These two module mates are designed to implement a program that responds to the user's keyboard input in real time. When you run the program, enter ' Q ' to exit the program directly, without having to press ENTER.
$ first Gets the current terminal configuration
old_settings = termios.tcgetattr (FD)
$ sets the terminal as a non-blocking input method that responds to keyboard input by character
Tty.setraw (FD)
$ restore Terminal configuration
Termios.tcgetattr (FD, Termios. Tcsadrain, Old_settings)
"Python at Work" Random name small script