Shift + Return to insert a row in python

I am trying to get the behavior of typical IM clients that use Return to send text and Shift + Return to insert a row. Is there a way to achieve this with minimal effort in Python using, for example, readline and raw_input ?

+8
python input readline
source share
4 answers

Well, I heard that this can also be done with readline .

You can import readline and configure the desired key (Shift + Enter) on the macro, which places some special char at the end of the line and new line. Then you can call raw_input in a loop.

Like this:

 import readline # I am using Ctrl+K to insert line break # (dont know what symbol is for shift+enter) readline.parse_and_bind('Ck: "#\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) 
+2
source share

I doubt that you can only do this with the readline module, since it will not capture individual keystrokes, but simply processes character responses from your input driver.

You can do this with PyHook , although if you press the Shift along with the Enter key to enter a new-line into the readline stream.

+1
source share

I think that with minimal effort you can use the urwid library for Python. Unfortunately, this does not meet your requirement to use readline / raw_input.

Update: see also this answer for another solution.

+1
source share
 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('Cx: "\x16\n"') # \x16 is Cv 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 
0
source share

All Articles