8

我试图了解Return用于发送文本和Shift + Return插入换行符的典型 IM 客户端的行为。有没有办法在 Python 中以最小的努力实现这一点,例如使用readlineraw_input

4

4 回答 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 回答
1

我认为你可以用最小的努力使用 Python 的urwid库。不幸的是,这不能满足您使用 readline/raw_input 的要求。

更新:有关其他解决方案,另请参阅此答案

于 2012-07-05T11:30:35.443 回答
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 回答