0

I am preparing a very simple script and I need the user to input certain values. At a certain point, I want to offer the chance to reuse an existing value or delete it if the user input is the DELETE key (the user presses DELETE and then Enter) but I don't seem to be able to find a satisfactory answer (which I find rather surprising...) It's just a helper script, so I was trying to avoid more advanced stuff such as PyHook and things like that.

This is the chunk I'm interested in:

if reusable_params:
    for key in list(k for k in config_dict.keys() if k not in ["mac", "base_url", "command_name"]):
        msg = "Enter new value for parameter {0}. Press ENTER to reuse the previous {1}. Press DELETE+ENTER to remove this key.".format(key, config_dict[key])
        input = unicode(raw_input(msg).strip().decode(sys.stdin.encoding))
        logging.debug("input: %s, len(input) %s" % (input, len(input))

Pressing DELETE+Enter returns a unicode looking 4 characters string:

enter image description here

Thank you in advance!

4

2 回答 2

2

您可能想看看pykeylogger,允许您捕获键盘事件,另一个选项是使用pygame,它有很好的键事件支持。

对于pygame

具体来说,您可能想看看这个页面( pygame.keys),

K_DELETE              delete #thanks to @7stud

所以你可能可以做这样的事情,

key = pygame.key.get_pressed()
        if key[pygame.K_DELETE]:
           #your code here...

对于pykeylogger, 从这里:

import keylogger
import time

now = time.time()
done = lambda: time.time() > now + 60
def print_keys(t, modifiers, keys): print "%.2f   %r   %r" % (t, keys, modifiers)

keylogger.log(done, print_keys)
于 2013-08-16T16:07:12.517 回答
1

您的 cmd 窗口是一个软件,即一个计算机程序。当您在 cmd 窗口中按下 delete 键时,cmd 窗口会被编程,因此它不会将 delete 键 (127) 的 ascii 代码添加到存储到目前为止输入的所有击键的数组中,即输入缓冲区。相反,当您按下删除键时,cmd 窗口会被编程为从数组中删除最后一次击键。它很简单:

key_strokes = []

#get key_code

if key_code == 127:
    key_strokes.pop()
else:
    key_strokes.append(key_code)

问题是您需要控制生成 cmd 窗口的程序以更改其行为方式。

最简单的解决方案是让您的用户输入一个“d”来删除——而不是按下删除键。

否则,您需要在用户键入时捕获击键。响应击键(而不是等待 Enter 键)的最佳和最有效的方法是了解 Tkinter。您可以向您的用户展示您创建的窗口——所谓的 GUI,并且您可以对其进行编程以在用户按下删除键时执行任何您想做的事情:

import Tkinter as tk

root = tk.Tk()
root.geometry("300x200")

entry = tk.Entry(root)
entry.pack()

def get_key(event):
    print "You pressed", repr(event.char)
entry.bind("<Key>", get_key)

root.mainloop()

做类似事情的另一种方法是使用 curses 模块,这是一个巨大的时间浪费。你花在整理诅咒上的时间最好花在学习 Tkinter 上。

现在,您的代码中发生了什么:

list(k for k in config_dict.keys() if k not in ["mac", "base_url", "command_name"]):

为什么要创建一个生成器,然后在从生成器中提取列表后立即将其丢弃?消除生成器步骤有什么问题:

[
    k for k in config_dict.keys() 
    if k not in ["mac", "base_url", "command_name"]
]

如果您为“nots”使用集合而不是列表,则效率会更高。必须搜索整个列表并不像一个字典查找那样有效:

[
    k for k in config_dict.keys() 
    if k not in set(["mac", "base_url", "command_name"])
]
于 2013-08-16T16:00:19.007 回答