gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:30:03 27 4
gpt4 key购买 nike

假设我有一个 python 程序,它会输出文本行,例如:

while 1:
print "This is a line"

允许用户按下键盘上的某个键来暂停循环,然后再次按下则恢复 - 但如果没有按下任何按钮,它应该自动继续进行,最简单的方法是什么?

我希望我不必陷入诸如诅咒之类的事情来得到这个!

最佳答案

您可以在 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

关于python - 暂停命令行 python 程序的最简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3894408/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com