比方說,我有一個Python程序,咳出來的文本行,如:暫停命令行python程序的最簡單方法?
while 1:
print "This is a line"
什麼是允許一個按鍵盤上的一個鍵暫停循環,然後恢復,如果最簡單的方法再次按---但如果沒有按下它應該只是自動繼續?
我希望我不必進入像詛咒這樣的東西來得到這個!
比方說,我有一個Python程序,咳出來的文本行,如:暫停命令行python程序的最簡單方法?
while 1:
print "This is a line"
什麼是允許一個按鍵盤上的一個鍵暫停循環,然後恢復,如果最簡單的方法再次按---但如果沒有按下它應該只是自動繼續?
我希望我不必進入像詛咒這樣的東西來得到這個!
你可以嘗試爲Linux的/的Mac(以及可能的其他Unix系統)(代碼歸屬: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
爲我,假設我在bash工作的最簡單的方法,將按下Control-Z暫停工作,然後使用'fg'命令在我準備好時恢復它。但由於我不知道您使用的是哪個平臺,因此我必須使用ChristopheD的解決方案作爲您的最佳起點。
Dupe:http://stackoverflow.com/questions/577467/pause-in-python ??? – 2010-10-08 21:28:58
你正在使用哪個操作系統? – ktdrv 2010-10-08 21:29:27
@Preet Sangha:我不會說這是重複的。這裏的問題是,如果*用戶*希望它停止,程序就會暫停,並且您所指的是關於在* it *時想讓程序暫停的問題。 – ktdrv 2010-10-08 21:31:23