I'm trying to get the behaviour of typical IM clients that use Return
to send a text and Shift + Return
to insert a linebreak. Is there a way to achieve that with minimal effort in Python, using e.g. readline and raw_input
?
In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line. Essentially the occurrence of the “\n” indicates that the line ends here and the remaining characters would be displayed in a new line.
"\r\n" is the default Windows style for line separator. "\r" is classic Mac style for line separator.
If you have a very long line of code in Python and you'd like to break it up over over multiple lines, if you're inside parentheses, square brackets, or curly braces you can put line breaks wherever you'd like because Python allows for implicit line continuation.
Ok, I heard it can be accomplished also with the readline
, in a way.
You can import readline
and set in configuration your desired key (Shift+Enter) to a macro that put some special char to the end of the line and newline. 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('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)
I doubt you'd be able to do that just using the readline
module as it will not capture the individual keys pressed and rather just processes the character responses from your input driver.
You could do it with PyHook though and if the Shift
key is pressed along with the Enter
key to inject a new-line into your readline
stream.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With