Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple lines user input in command-line Python application

Is there any easy way to handle multiple lines user input in command-line Python application?

I was looking for an answer without any result, because I don't want to:

  • read data from a file (I know, it's the easiest way);
  • create any GUI (let's stay with just a command line, OK?);
  • load text line by line (it should pasted at once, not typed and not pasted line by line);
  • work with each of lines separately (I'd like to have whole text as a string).

What I would like to achieve is to allow user pasting whole text (containing multiple lines) and capture the input as one string in entirely command-line tool. Is it possible in Python?

It would be great, if the solution worked both in Linux and Windows environments (I've heard that e.g. some solutions may cause problems due to the way cmd.exe works).

like image 366
kurp Avatar asked Sep 19 '12 11:09

kurp


People also ask

How do you input multiple lines from user in Python?

1st Method: inputlist = [] while True: try: line = input() except EOFError: break inputlist. append(line) 2nd Method import sys inputlist = sys. stdin. readlines() print(inputlist) This will take multi-line input however you need to terminate the input (ctrl+d or ctrl+z).

How do you type multiple lines in Python terminal?

You cannot split a statement into multiple lines in Python by pressing Enter . Instead, use the backslash ( \ ) to indicate that a statement is continued on the next line. In the revised version of the script, a blank space and an underscore indicate that the statement that was started on line 1 is continued on line 2.


2 Answers

import sys

text = sys.stdin.read()

After pasting, you have to tell python that there is no more input by sending an end-of-file control character (ctrl+D in Linux, ctrl+Z followed by enter in Windows).

This method also works with pipes. If the above script is called paste.py, you can do

$ echo "hello" | python paste.py

and text will be equal to "hello\n". It's the same in windows:

C:\Python27>dir | python paste.py

The above command will save the output of dir to the text variable. There is no need to manually type an end-of-file character when the input is provided using pipes -- python will be notified automatically when the program creating the input has completed.

like image 148
Lauritz V. Thaulow Avatar answered Nov 14 '22 21:11

Lauritz V. Thaulow


You could get the text from clipboard without any additional actions which raw_input() requires from a user to paste the multiline text:

import Tkinter
root = Tkinter.Tk()
root.withdraw()

text = root.clipboard_get()

root.destroy()

See also How do I copy a string to the clipboard on Windows using Python?

like image 43
jfs Avatar answered Nov 14 '22 21:11

jfs