我试图了解Return
用于发送文本和Shift + Return
插入换行符的典型 IM 客户端的行为。有没有办法在 Python 中以最小的努力实现这一点,例如使用readline和raw_input
?
问问题
3570 次
4 回答
2
好的,我听说它也可以通过readline
, 以某种方式完成。
您可以import readline
在配置中将所需的键 (Shift+Enter) 设置为一个宏,该宏将一些特殊字符置于行尾和换行符。然后你可以raw_input
循环调用。
像这样:
import readline
# I am using Ctrl+K to insert line break
# (dont know what symbol is for shift+enter)
readline.parse_and_bind('C-k: "#\n"')
text = []
line = "#"
while line and line[-1]=='#':
line = raw_input("> ")
if line.endswith("#"):
text.append(line[:-1])
else:
text.append(line)
# all lines are in "text" list variable
print "\n".join(text)
于 2012-07-05T12:19:08.180 回答
1
我怀疑您是否能够仅使用该readline
模块来做到这一点,因为它不会捕获按下的各个键,而只会处理来自输入驱动程序的字符响应。
不过,您可以使用PyHook来做到这一点,并且如果该Shift
键与该Enter
键一起按下以将换行符注入您的readline
流中。
于 2012-07-05T11:30:25.583 回答
0
import readline
# I am using Ctrl+x to insert line break
# (dont know the symbols and bindings for meta-key or shift-key,
# let alone 4 shift+enter)
def startup_hook():
readline.insert_text('» ') # \033[32m»\033[0m
def prmpt():
try:
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set editing-mode vi')
readline.parse_and_bind('C-x: "\x16\n"') # \x16 is C-v which writes
readline.set_startup_hook(startup_hook) # the \n without returning
except Exception as e: # thus no need 4 appending
print (e) # '#' 2 write multilines
return # simply use ctrl-x or other some other bind
while True: # instead of shift + enter
try:
line = raw_input()
print '%s' % line
except EOFError:
print 'EOF signaled, exiting...'
break
# It can probably be improved more to use meta+key or maybe even shift enter
# Anyways sry 4 any errors I probably may have made.. first time answering
于 2017-04-02T07:53:08.383 回答