How to accept command-line args ending in backslash

The backslash 'escapes' the character following it. This means that the closing quotation marks become a part of the argument, and don't actually terminate the string.

This is the behaviour of the shell you're using (presumably bash or similar), not Python (although you can escape characters within Python strings, too).

The solution is to escape the backslashes:

python args.py "hello\world\\"

Your Python script should then function as you expect it to.


The backslash at the end is interpreted as the start of an escape sequence, in this case a literal double quote character. I had a similar problem with handling environment parameters containing a path that sometimes ended with a \ and sometimes didn't.
The solution I came up with was to always insert a space at the end of the path string when calling the executable. My executable then uses the directory path with the slash and a space at the end, which gets ignored. You could possibly trim the path within the program if it causes you issues.

If %SlashPath% = "hello\"

python args.py "%SlashPath% " world "any cpu"
Arguments:
[0] = args.py
[1] = hello\ 
[2] = world
[3] = any cpu

If %SlashPath% = "hello"

python args.py "%SlashPath% " world "any cpu"
Arguments:
[0] = args.py
[1] = hello 
[2] = world
[3] = any cpu

Hopefully this will give you some ideas of how to get around your problem.


That's likely the shell treating \ as an escape character, and thus escaping the character. So the shell sends \" as " (because it thinks you are trying to escape the double quote). The solution is to escape the escape character, like so: $ python args.py "hello\world\\".


The Microsoft Parameter Parsing Rules

These are the rules for parsing a command line passed by CreateProcess() to a program written in C/C++:

  1. Parameters are always separated by a space or tab (multiple spaces/tabs OK)
  2. If the parameter does not contain any spaces, tabs, or double quotes, then all the characters in the parameter are accepted as is (there is no need to enclose the parameter in double quotes).
  3. Enclose spaces and tabs in a double quoted part
  4. A double quoted part can be anywhere within a parameter
  5. 2n backslashes followed by a " produce n backslashes + start/end double quoted part
  6. 2n+1 backslashes followed by a " produce n backslashes + a literal quotation mark
  7. n backslashes not followed by a quotation mark produce n backslashes
  8. If a closing " is followed immediately by another ", the 2nd " is accepted literally and added to the parameter (This is the undocumented rule.)

For a detailed and clear description see http://www.daviddeley.com/autohotkey/parameters/parameters.htm#WINCRULESDOC