The python implementation presses any key to continue executing the program

  • 2020-05-19 05:02:02
  • OfStack

When writing bat under windows, you can pause the program through the pause command. For example, the frequently seen program will prompt "press any key to continue..." at the terminal. , the user terminal after enter the program can then run, regardless of how much this function use today, but I think there should be a lot of people also want to realize this function, under python when writing your own python program is running, all of a sudden give a hint, so then myself to a handsome return, I think certainly the sense that gives a person a kind of very professional, at the very least, oneself must be charmed, so today we will learn the code, it defines a function, so you can be embedded into your program, in any place you want to call calls it, use very convenient, The code is as follows:


#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import sys
import termios
def press_any_key_exit(msg):
#  Gets the descriptor for standard input 
fd = sys.stdin.fileno()
#  Get standard input ( terminal ) The setting of the 
old_ttyinfo = termios.tcgetattr(fd)
#  Configure the terminal 
new_ttyinfo = old_ttyinfo[:]
#  Use non-canonical patterns ( The index 3 is c_lflag  That's the local mode )
new_ttyinfo[3] &= ~termios.ICANON
#  Close the echo ( The input will not be displayed )
new_ttyinfo[3] &= ~termios.ECHO
#  Output information 
sys.stdout.write(msg)
sys.stdout.flush()
#  Enable Settings 
termios.tcsetattr(fd, termios.TCSANOW, new_ttyinfo)
#  Read from terminal 
os.read(fd, 7)
#  Restore terminal setting 
termios.tcsetattr(fd, termios.TCSANOW, old_ttyinfo)
if __name__ ==  " __main__ " :
press_any_key_exit( "Press any key to continue..." )
print  ' \n'

Code is not much to explain, see comments, here to say 1 termios module, this module provides an interface to control Io tty terminal, all its functions first parameters requires a file descriptor, can be a integer file descriptors, also can is a file object, because it can control the terminal display Settings, common scenario is the user terminal don't displayed, enter the password as we landed in root system input password prompt system is one kind, code implementation is as follows:


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
try:
termios.tcsetattr(fd, termios.TCSADRAIN, new)
passwd = raw_input(prompt)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
return passwd
passwd = getpass()
print passwd

This script will prompt you to enter the password, after the input will print out the password just entered, to give this 2 examples is also to illustrate the simple use of termios, you can run the program to experience.


Related articles: