How to end python input() with Ctrl+Enter and use enter for new line?

  • 1 year ago
Comment

1 / 1

By default, the input() function in Python terminates input when the user presses the Enter key. However, you can modify this behavior by using the readline() function from the readline module.

Here's an example of how to use readline() to end input with Ctrl+Enter and use Enter for new lines:

python
import readline

def input_multiline(prompt=""):
print(prompt)
line = ""
while True:
char = readline.getch()
if char == b'\x03': # Ctrl+C
raise KeyboardInterrupt
elif char == b'\r': # Enter
print()
return line
elif char == b'\n': # Ctrl+Enter
line += '\n'
else:
line += char.decode("utf-8")

In this example, readline.getch() is used to read a single character from the input, without waiting for Enter. If the user presses Ctrl+Enter, a newline character \n is added to the input string line. If the user presses Enter, the input is terminated and the function returns the input string.

To use this function, simply call input_multiline() instead of input(). You can pass an optional prompt string as an argument.

Note that this function may not work correctly in all terminal environments, and may behave differently on different platforms.