Issue
Here's a barebones Python app that simply prints the command-line arguments passed in:
import sys
if __name__ == "__main__":
print "Arguments:"
for i in range(len(sys.argv)):
print "[%s] = %s" % (i, sys.argv[i])
And here's some sample runs:
python args.py hello world
Arguments:
[0] = args.py
[1] = hello
[2] = world
python args.py "hello world"
Arguments:
[0] = args.py
[1] = hello world
python args.py "hello\world"
Arguments:
[0] = args.py
[1] = hello\world
So far so good. But now when I end any argument with a backslash, Python chokes on it:
python args.py "hello\world\"
Arguments:
[0] = args.py
[1] = hello\world"
python args.py "hello\" world "any cpu"
Arguments:
[0] = args.py
[1] = hello" world any
[2] = cpu
I'm aware of Python's less-than-ideal raw string behavior via the "r" prefix (link), and it seems clear that it's applying the same behavior here.
But in this case, I don't have control of what arguments are passed to me, and I can't enforce that the arguments don't end in a backslash. How can I work around this frustrating limitation?
--
Edit: Thanks to those who pointed out that this behavior isn't specific to Python. It seems to be standard shell behavior (at least on Windows, I don't have a Mac at the moment).
Updated question: How can I accept args ending in a backslash? For example, one of the arguments to my app is a file path. I can't enforce that the client sends it to me without a trailing backslash, or with the backslash escaped. Is this possible in any way?
Solution
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.
Answered By - Anthony K Answer Checked By - Robin (WPSolving Admin)