Python, Press Any Key To Exit

后端 未结 9 1289
渐次进展
渐次进展 2020-12-31 06:16

So, as the title says, I want a proper code to close my python script. So far, I\'ve used input(\'Press Any Key To Exit\'), but what that does, is generate a er

9条回答
  •  醉话见心
    2020-12-31 06:57

    Here's a way to end by pressing any key on *nix, without displaying the key and without pressing return. (Credit for the general method goes to Python read a single character from the user.) From poking around SO, it seems like you could use the msvcrt module to duplicate this functionality on Windows, but I don't have it installed anywhere to test. Over-commented to explain what's going on...

    import sys, termios, tty
    
    stdinFileDesc = sys.stdin.fileno() #store stdin's file descriptor
    oldStdinTtyAttr = termios.tcgetattr(stdinFileDesc) #save stdin's tty attributes so I can reset it later
    
    try:
        print 'Press any key to exit...'
        tty.setraw(stdinFileDesc) #set the input mode of stdin so that it gets added to char by char rather than line by line
        sys.stdin.read(1) #read 1 byte from stdin (indicating that a key has been pressed)
    finally:
        termios.tcsetattr(stdinFileDesc, termios.TCSADRAIN, oldStdinTtyAttr) #reset stdin to its normal behavior
        print 'Goodbye!'
    

提交回复
热议问题