Python 获得键盘输入而不会卡住
Python get keyboard input without getting stuck
我正在制作一个 python 程序,每小时更换一次壁纸,但我希望在按下某个按钮时也能更换壁纸。
这是我试过的代码
while True:
key = ord(getch())
但唯一不好的部分是它一直卡在上面,直到我按下某些东西。有更好的方法吗?
您也许可以通过使用 https://pypi.python.org/pypi/pynput 来实现您想要的效果。
另请参阅其在 pythonhosted 上的文档 http://pythonhosted.org/pynput/, especially the section about monitoring the keyboard http://pythonhosted.org/pynput/keyboard.html#monitoring-the-keyboard。
以下是文档中的示例:
from pynput.keyboard import Key
from pynput.keyboard import Listener
def on_press(key):
print('{0} pressed'.format(
key))
def on_release(key):
print('{0} release'.format(
key))
if key == Key.esc:
# Stop listener
return False
# Collect events until released
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
它将打印您按下的每个键,直到您按下 ESC,之后它将终止。
请注意,有一些特定于操作系统的事情需要考虑,例如在 OSX 上,进程必须 运行 作为 root。
我不知何故无意中发现了这个。
import msvcrt
if msvcrt.kbhit():
Key = ord(getch())
if Key ==96:
#Do something here
这似乎行得通。我认为 msvcrt.kbhit() 正在等待按键。 Key = ord(getch()) 接受按键,如果 Key ==96: 检查它是否是正确的按键
我正在制作一个 python 程序,每小时更换一次壁纸,但我希望在按下某个按钮时也能更换壁纸。
这是我试过的代码
while True:
key = ord(getch())
但唯一不好的部分是它一直卡在上面,直到我按下某些东西。有更好的方法吗?
您也许可以通过使用 https://pypi.python.org/pypi/pynput 来实现您想要的效果。
另请参阅其在 pythonhosted 上的文档 http://pythonhosted.org/pynput/, especially the section about monitoring the keyboard http://pythonhosted.org/pynput/keyboard.html#monitoring-the-keyboard。
以下是文档中的示例:
from pynput.keyboard import Key
from pynput.keyboard import Listener
def on_press(key):
print('{0} pressed'.format(
key))
def on_release(key):
print('{0} release'.format(
key))
if key == Key.esc:
# Stop listener
return False
# Collect events until released
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
它将打印您按下的每个键,直到您按下 ESC,之后它将终止。
请注意,有一些特定于操作系统的事情需要考虑,例如在 OSX 上,进程必须 运行 作为 root。
我不知何故无意中发现了这个。
import msvcrt
if msvcrt.kbhit():
Key = ord(getch())
if Key ==96:
#Do something here
这似乎行得通。我认为 msvcrt.kbhit() 正在等待按键。 Key = ord(getch()) 接受按键,如果 Key ==96: 检查它是否是正确的按键