python从键盘上输入_如何用Python读取键盘输入

例如,有一个Python代码如下:

文件1.py#!/bin/python

... do some stuff...

在文档的某一点上,您要始终检查输入:while True:

input = raw_input(">>>")

... do something with the input...

这将永远等待输入。您可以将这个无限循环作为一个单独的进程进行线程处理,同时执行其他操作,这样用户输入就可以在您正在执行的任务中产生效果。

如果您只想在按下某个键时请求输入,并将其作为循环执行,那么使用此代码(取自this ActiveState recipe by Steven D'Aprano),您可以等待按键发生,然后请求输入,执行任务并返回到上一个状态。import sys

try:

import tty, termios

except ImportError:

# Probably Windows.

try:

import msvcrt

except ImportError:

# FIXME what to do on other platforms?

# Just give up here.

raise ImportError('getch not available')

else:

getch = msvcrt.getch

else:

def getch():

"""getch() -> key character

Read a single keypress from stdin and return the resulting character.

Nothing is echoed to the console. This call will block if a keypress

is not already available, but will not wait for Enter to be pressed.

If the pressed key was a modifier key, nothing will be detected; if

it were a special function key, it may return the first character of

of an escape sequence, leaving additional characters in the buffer.

"""

fd = sys.stdin.fileno()

old_settings = termios.tcgetattr(fd)

try:

tty.setraw(fd)

ch = sys.stdin.read(1)

finally:

termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

return ch

那怎么处理呢?好吧,现在只要每次你想等一次按键就给getch()打电话。就像这样:while True:

getch() # this also returns the key pressed, if you want to store it

input = raw_input("Enter input")

do_whatever_with_it

你也可以线程,并在同一时间做其他的任务。

请记住,Python3.x不再使用原始输入,而只使用input()。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值