Multiple lines user input in command-line Python application

前端 未结 3 1286
清歌不尽
清歌不尽 2021-01-05 13:30

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, becaus

相关标签:
3条回答
  • 2021-01-05 14:09
    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.

    0 讨论(0)
  • 2021-01-05 14:22

    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?

    0 讨论(0)
  • 2021-01-05 14:26

    Use :

    input = raw_input("Enter text")

    These gets in input as a string all the input. So if you paste a whole text, all of it will be in the input variable.

    EDIT: Apparently, this works only with Python Shell on Windows.

    0 讨论(0)
提交回复
热议问题