I am working on a script with user input in Py 3.6.
In the script, the user is asked to enter a text section - potentially containing new lines - into the shell. The entered text will then be saved to a Python variable for further processing.
Since the user input may contain newlines, I think I cannot use input()
but am using sys.stdin.read()
(as suggested here).
Reading in the input works fine, but to end the user input, the user has to hit Return and then use the key combination CTRL + d
(see here). (See Current Procedure below)
sys.stdin.read
by hitting the Return key (cf Expected Procedure below) EDIT: Any other simplification to the current process with CTRL + d
is appreciated as well.
Is this doable?
There are some hacks here but I thought maybe there is a better way
# display text on screen
print("Review this text\n" + text)
# user will copy and paste relevant items from text displayed into Terminal
user_input = sys.stdin.read()
print ("hit ctrl + d to continue")
# process `user_input`
With the current code reproduced below, the user has to
1) paste the text
2) hit RETURN
to end input
3) hit Ctrl+d
to move to next file
I would like to reduce this to:
1) paste the text
2) hit RETURN
to end input and move to next file
Running Python 3.5.6 on MacOSX, using Terminal for text input. Any help is much appreciated!
Based on your reply in the comment, if terminating by empty line is acceptable (i.e. your input text cannot contain newline on its own except to terminate input), that is quote trivial:
user_input = '' # User input we'll be adding to
for line in sys.stdin: # Iterator loops over readline() for file-like object
if line == '\n': # Got a line that was just a newline
break # Break out of the input loop
user_input += line # Keep adding input to variable
The other option I've been mentioning, even though I do not really like the assumptions underpinning this approach. You can read your input and record time of each entered. You can define a time limit after which you are comfortable to assume it was not part of copy paste as a single block. And following newline on its own is then assumed to be end of user input. For instance:
import sys
import time
COPY_PASTE_LIMIT = 0.5 # For instance 500ms
# Presuming platform time precision
# greater then whole seconds.
user_input = ''
last = 0 # We'll also later terminate when input was nothing
# but an initial empty line.
for line in sys.stdin:
now = time.time()
if line == '\n' and (now - last > COPY_PASTE_LIMIT or last == 0):
break
last = now
user_input += line
print(user_input)
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