8

I know about escaping backslashes in programming. However I'm passing in a command line argument into a Python program to parse. Whitespace is irrelevant, however via the command line, whitespace does matter. So I am trying to concatenate all argv[] arguments except the first element into a string to then parse. However a token of a single '\' is never encountered in the for loop.

The command line argument (notice whitespace around '\'):

((1 * 2) + (3 - (4 \ 5)))

Program:

import sys
string = ""
for token in sys.argv[1:len(sys.argv)]:
    print(token)
    if "\\" in r"%r" % token:
        print("Token with \\ found")
    string += token
print(string)
print("done")
tfbbt8
  • 325
  • 4
  • 13
  • 4
    Why don't you pass the whole expression as a single argument? `python myscript.py '((1 * 2) + (3 - (4 \ 5)))'`. Also, bash considers \ as a beginning of an escape sequence and doesn't send it through as an argument, but cmd doesn't and sends it normally, that gives different behaviour on different OS. – Kolmar Jan 26 '15 at 17:51
  • I agree with @Kolmar, it would make things much easier in python, and you don't have to worry what the shell does to your arguments – Paco Jan 26 '15 at 17:54

1 Answers1

5

This is not a Python problem. The shell will interpret the text you write at the command line and (for typical Unix shells) perform backslash substitution. So by the time Python examines the command line, the backslash will already have been substituted away.

The workaround is to double the backslash or put it in single quotes, if your shell is Bash or some other Bourne-compatible Unix shell. Windows CMD is different and bewildering in its own right; Csh doubly so.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Thanks friend. It's for an assignment and I was just going by the pdf which showed it being passed without quotes. Using single quotes fixed the issue completely. Thanks again! – tfbbt8 Jan 27 '15 at 21:46