Wolfger
Wolfger

Reputation: 191

Can python input handle inline \n?

I am trying to write a program that will accept user input which will be a pasted block of text (including multiple newlines/carriage-returns). I'm having trouble finding info on how (if) Python can handle this. Normal behavior is for the input command to complete as soon as the first \n is encountered.

Upvotes: 1

Views: 453

Answers (1)

Gavin Anderegg
Gavin Anderegg

Reputation: 6391

When I first saw your question I read "input command" as "the command being input", not as "the input() function". I'm now assuming here that you're gathering data from the command line.

The problem with taking input with newlines in it is: when do you stop accepting input? The following example gets around this by waiting for the user to hit ctrl-d. This triggers an exception in the raw_input() function and then breaks out of the while loop.

text = ''

# keep looping forever
while True:
    try:
        # grab the data from the user, and add back the newline
        # which raw_input() strips off
        text += raw_input() + "\n"
    except EOFError:
        # if you encounter EOF (which ctrl-d causes) break out of the loop
        break

# print the text you've gathered after a dashed line
print "\n------------\n" + text

Obviously you'll want to warn your user that they'll have to use ctrl-d to stop entering text, which might be a bit awkward — but if they're already on the command prompt it shouldn't be so bad.

Also, here I've used raw_input(), which gathers input but doesn't exec() it as input() does. If you're looking to execute the results, you could just replace the print() call with :

exec(text)

to have similar results.

Upvotes: 4

Related Questions