python实现暂停一秒输出的效果_最简单的方法暂停命令行python程序?

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 to allow one to press a key on the keyboard to pause the loop, then to resume if pressed again---but if nothing is pressed it should just continue on automatically?

I'm hoping I don't have to go into something like curses to get this!

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值