Shift + Return在python中插入换行符

时间:2012-07-05 11:24:11

标签: python input readline

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

4 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

我怀疑你只能使用readline模块,因为它不会捕获按下的各个键,而只是处理来自输入驱动程序的字符响应。

您可以使用PyHook执行此操作,如果Shift键与Enter键一起按下,则会在readline流中注入新行。< / p>

答案 2 :(得分:1)

我认为只需很少的工作量就可以使用urwid库来实现Python。不幸的是,这不符合您使用readline / raw_input的要求。

更新:另请参阅this answer了解其他解决方案。

答案 3 :(得分: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