有没有办法从用户输入读取一个单个字符?例如,他们在终端按一个键然后返回(有点像getch()
).我知道Windows中有一个功能,但我想要一些跨平台的功能.
如何从控制台python应用程序轮询键盘?具体来说,我想在许多其他I/O活动(套接字选择,串行端口访问等)中做类似的事情:
while 1:
# doing amazing pythonic embedded stuff
# ...
# periodically do a non-blocking check to see if
# we are being told to do something else
x = keyboard.read(1000, timeout = 0)
if len(x):
# ok, some key got pressed
# do something
Run Code Online (Sandbox Code Playgroud)
在Windows上执行此操作的正确pythonic方法是什么?此外,Linux的可移植性也不错,但并不是必需的.
我必须知道按下了什么键,但不需要字符的代码,我想知道当有人按下'A'键时,即使获得的键是'a'或'A',所以其他键都是如此.
我不能使用PyGame或任何其他库(包括Tkinter).只有Python标准库.这必须在终端中完成,而不是图形界面.
不需要字符代码.我需要知道关键代码.
例如:
ord('a') != ord('A') # 97 != 65
someFunction('a') == someFunction('A') # a_code == A_code
Run Code Online (Sandbox Code Playgroud) 我被困在这里(下图),需要通过它才能读取我的文本。我还有 text.txt 文件。该程序本身无法使用 python 2 运行。使用 python 2 它在这里给了我一个错误:print(last_suggestion, end=' ', flush=True)
。
train_data = 'text.txt'
first_possible_words = {}
second_possible_words = {}
transitions = {}
def expandDict(dictionary, key, value):
if key not in dictionary:
dictionary[key] = []
dictionary[key].append(value)
def get_next_probability(given_list): #returns dictionary
probability_dict = {}
given_list_length = len(given_list)
for item in given_list:
probability_dict[item] = probability_dict.get(item, 0) + 1
for key, value in probability_dict.items():
probability_dict[key] = value / given_list_length
return probability_dict
def trainMarkovModel():
for line in open(train_data):
tokens = line.rstrip().lower().split() …
Run Code Online (Sandbox Code Playgroud) 我想知道如何在不需要按 Enter 的情况下接受输入。我在网上搜索,我得到了一些关于 raw_input 的信息,但我认为在 python 3.0 到来后它变得过时了。有时,我会在整个程序上运行一个 while 循环,因为我想问用户:继续吗?(是/否):
例如考虑代码:
import random
d = input('Toss coin? (y/n): ')
while d != 'n' and d!= 'N':
c = random.randint(1,2)
if c == 1:
print('HEADS!')
else:
print('TAILS!')
d = input('Toss coin? (y/n): ')
Run Code Online (Sandbox Code Playgroud)
但我只想通过不让用户每次都按 Enter 来为我的程序添加更多光晕。只需按 y 或 n,程序就会相应地循环或中断。
好的,这是新代码:
import random
import msvcrt
d = input('Toss coin? (y/n): ')
while d != 'n' and d!= 'N':
c = random.randint(1,2)
if c == 1:
print('HEADS!')
else:
print('TAILS!')
print('Toss coin? (y/n): ') …
Run Code Online (Sandbox Code Playgroud) python ×4
input ×2
python-3.x ×2
blocking ×1
console ×1
keyboard ×1
keycode ×1
macos ×1
msvcrt ×1
nonblocking ×1
user-input ×1
while-loop ×1