2012-07-05 61 views
8

我試圖獲取使用Return發送文本的插入換行符的典型IM客戶端的行爲。有沒有一種方法可以在Python中以最小的努力實現這一點,例如使用readlineraw_inputShift + Return在python中插入換行符

+0

您是否在尋找平臺相關或無關的答案? – Jiri 2012-07-05 11:33:39

+0

如果可能,獨立於平臺,但* nix兼容應該作爲應用程序的目標命令行用戶。 – 2012-07-05 11:38:23

回答

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

我懷疑你只需要使用readline模塊就可以做到這一點,因爲它不會捕獲按下的各個按鍵,而只是處理來自輸入驅動程序的字符響應。

您可以用PyHook做到這一點,雖然,如果Shift密鑰與Enter鍵一起按下注入了新的行到您的readline流。

+0

謝謝,但我想保持平臺與* nix的兼容性! – 2012-07-05 11:32:42

1

我認爲用最少的努力你可以使用urwid庫的Python。不幸的是,這不符合您使用readline/raw_input的要求。

更新:另請參閱this answer其他解決方案。

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