暂停命令行python程序最简单的方法?

时间:2010-10-08 21:23:28

标签: python command-line

假设我有一个python程序正在吐出文本行,例如:

while 1:
  print "This is a line"

最简单的方法是让一个人按下键盘上的按键来暂停循环,然后再次按下则恢复 - 但如果没有按任何按钮它应该自动继续?

我希望我不必像诅咒一样去做这件事!

3 个答案:

答案 0 :(得分:4)

您可以尝试 Linux / Mac (以及可能的其他Unices)的此实现(代码归属:found on ActiveState Code Recipes)。

Windows 上,您应该查看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 <> []

实现你正在寻找的东西会变成这样:

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

答案 1 :(得分:2)

的最简单方法,假设我在bash中工作,就是按Control-Z暂停作业,然后在我准备好时使用'fg'命令恢复它。但由于我不知道你正在使用什么平台,我将不得不使用ChristopheD的解决方案作为你的最佳起点。

答案 2 :(得分:0)

当您按Ctrl + C组合键时,程序中会引发KeyboardInterrupt异常。您可以捕获该异常以创建所需的行为-例如,暂停程序并在5秒后恢复:

import time

while True:
     try:
         # This is where you're doing whatever you're doing
         print("This is a line")
     except KeyboardInterrupt:
         print("Paused! Ctrl+C again within 5 seconds to kill program")
         # A second KeyboardInterrupt that happens during this sleep will
         # not be caught, so it will terminate the program
         time.sleep(5)
         print("Continuing...")

或者无限期地暂停程序,直到用户点击“ enter”:

while True:
     try:
         # This is where you're doing whatever you're doing
         print("This is a line")
     except KeyboardInterrupt:
         print("Interrupted!")
         input("Press enter to continue, or Ctrl+C to terminate.")
         print("Continuing...")

如果您还想抓紧第二个KeyboardInterrupt并做一些花哨的事情,可以通过嵌套try/except块来实现,尽管我不建议这样做-这是一个好主意允许一串KeyboardInterrupt终止程序。

相关问题