0

I am trying to force a binary input on the user and all is working expect when a user inputs a \n. The program just skips over that input thus throwing a out of index error on a list latter on.

    payload = input("Input the binary data payload: ") 
for i in str(payload):
        if (i == "0" or i == "1"):
Bob
  • 746
  • 3
  • 11
  • 26
  • How can the user input `\n`? Please provide an example. – arshajii Sep 17 '13 at 01:26
  • 1
    By "a user inputs a \n", do you mean that the user types a newline character, or that he types a backslash and then an n? – abarnert Sep 17 '13 at 01:27
  • 1
    Also, why are you doing `str(payload)`? `payload` is already a `str`. Are you trying to do some kind of conversion here? If so, what? – abarnert Sep 17 '13 at 01:27

2 Answers2

3

From the documentation:

The [input] function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

So the input function will never give you the \n. You'll have to find another function that reads in raw characters. This question may be useful.

Community
  • 1
  • 1
Sam Mussmann
  • 5,883
  • 2
  • 29
  • 43
1

Sam Mussmann's answer explains why what you're doing won't work.

But if you want to know how to fix it… I'm not entirely sure what you mean by "force a binary input".

How do you know when the input is done? For input, it's done as soon as the user hits a newline, so that clearly isn't what you want.

Also, input automatically decodes whatever the user gives it to give you a Unicode str. That's clearly not what you want here.

On top of that, input will use readline if it's available, which will cause various control characters to do line-editing stuff instead of just representing themselves.


If, say, you want to read everything until EOF, that's easy:

payload = sys.stdin.buffer.read()

… but note that in an interactive app, "until EOF" means "until the user hits ^D on a line by itself (Unix) or ^Z under some not-clearly-documented circumstances" (Windows)", which may not be very useful. It works great for shell input redirection, but you're talking about pasting into an interactive app.

If you want to read some fixed size, like 512 bytes, that's easy too, and doesn't have any such problems:

payload = sys.stdin.buffer.read(512)

It's hard to imagine anything else you could mean that makes sense. For example, it's pretty easy to read multiple lines up until a blank line, but binary data could easily have a blank line in the middle of it. Or anything else you can think of to use.

abarnert
  • 354,177
  • 51
  • 601
  • 671