Working with backslash as a command line argument in Python

I am aware of backslashes in programming. However, I pass the command line argument to the Python program for parsing. Spaces do not matter, but through the command line, spaces do matter. Therefore, I am trying to concatenate all argv [] arguments, except the first element, into a string, so that I can parse it later. However, the token of one "\" never occurs in a for loop.

Command line argument (notice the space 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") 
+5
source share
1 answer

This is not a Python issue. The shell interprets the text you write on the command line, and (for typical Unix shells) performs backslash substitution. So, by the time Python checks the command line, the backslash will already be replaced.

The workaround is to double the backslash or put it in single quotes if your Bash shell or some other Bourne compatible Unix shell. Windows CMD is different and confusing in itself; Csh is doubly.

+3
source

Source: https://habr.com/ru/post/1211941/


All Articles