Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with backslash as a command line argument in Python

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")
like image 727
tfbbt8 Avatar asked Jan 26 '15 17:01

tfbbt8


1 Answers

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.

like image 148
tripleee Avatar answered Oct 01 '22 17:10

tripleee