Python, Press Any Key To Exit

后端 未结 9 1167
渐次进展
渐次进展 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!'
    
    0 讨论(0)
  • 2020-12-31 07:00

    in Windows:

    if msvcrt.kbhit():
        if msvcrt.getch() == b'q':
            exit()
    
    0 讨论(0)
  • 2020-12-31 07:04

    I would discourage platform specific functions in python if you can avoid them, but you could use the built-in msvcrt module.

    from msvcrt import getch
    
    junk = getch() # Assign to a variable just to suppress output. Blocks until key press.
    
    0 讨论(0)
  • 2020-12-31 07:07

    As far as I know there is no way to 'press any key'. The input and raw_input commands require you to press the ENTER key. (raw_input is not supported in Python 3.x)

    0 讨论(0)
  • 2020-12-31 07:08

    Have you tried raw_input()? It could be that you are getting a syntax error by using input() on python 2.x, which will try to eval whatever it gets.

    0 讨论(0)
  • 2020-12-31 07:09

    A little late to the game, but I wrote a library a couple years ago to do exactly this. It exposes both a pause() function with a customizable message and the more general, cross-platform getch() function inspired by this answer.

    Install with pip install py-getch, and use it like this:

    from getch import pause
    pause()
    

    This prints 'Press any key to continue . . .' by default. Provide a custom message with:

    pause('Press Any Key To Exit.')
    

    For convenience, it also comes with a variant that calls sys.exit(status) in a single step:

    pause_exit(0, 'Press Any Key To Exit.')
    

    Check it out.

    0 讨论(0)
提交回复
热议问题