easiest way to pause a command-line python program?

前端 未结 3 1551
生来不讨喜
生来不讨喜 2021-01-07 05:24

Let\'s say I have a python program that is spitting out lines of text, such as:

while 1:
  print \"This is a line\"

What\'s the easiest way

3条回答
  •  梦谈多话
    2021-01-07 06:10

    You could try this implementation for Linux / Mac (and possible other Unices) (code attribution: found on ActiveState Code Recipes).

    On Windows you should check out msvcrt.

    import sys, termios, atexit
    from select import select
    
    # save the terminal settings
    fd = sys.stdin.fileno()
    new_term = termios.tcgetattr(fd)
    old_term = termios.tcgetattr(fd)
    
    # new terminal setting unbuffered
    new_term[3] = (new_term[3] & ~termios.ICANON & ~termios.ECHO)
    
    # switch to normal terminal
    def set_normal_term():
        termios.tcsetattr(fd, termios.TCSAFLUSH, old_term)
    
    # switch to unbuffered terminal
    def set_curses_term():
        termios.tcsetattr(fd, termios.TCSAFLUSH, new_term)
    
    def putch(ch):
        sys.stdout.write(ch)
    
    def getch():
        return sys.stdin.read(1)
    
    def getche():
        ch = getch()
        putch(ch)
        return ch
    
    def kbhit():
        dr,dw,de = select([sys.stdin], [], [], 0)
        return dr <> []
    

    Implementing what you're looking for would then become something like this:

    atexit.register(set_normal_term)
    set_curses_term()
    
    while True:
        print "myline"
        if kbhit():
            print "paused..."
            ch = getch()
            while True
                if kbhit():
                    print "unpaused..."
                    ch = getch()
                    break
    

提交回复
热议问题