2012-07-05 7 views
8

Returnを使用してテキストを送信し、Shift + Returnを使用して改行を挿入する一般的なIMクライアントの動作を取得しようとしています。 Pythonで最小限の労力でこれを達成する方法がありますか? readlineおよびraw_inputShift + Return to Pythonで改行を挿入する

+0

あなたは、プラットフォームに依存または独立した答えをお探しですか? – Jiri

+0

可能であれば、プラットフォームに依存しませんが、* nixとの互換性は、アプリケーションがコマンドラインユーザーをターゲットにしているために必要です。 –

答えて

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とのプラットフォームの互換性を維持したいと思います! –

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 
関連する問題