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?
To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments. The value of argc should be non negative. argv(ARGument Vector) is array of character pointers listing all the arguments.
A backslash followed by a newline character means the command continues to the next line. You could remove the backslash and type all of that on the same line if you wanted to. Follow this answer to receive notifications.
option. You can test command line arguments by running an executable from the "Command Prompt" in XP, Vista or later, or from the "DOS prompt" in older versions of Windows. You can also use command line arguments in program shortcuts, or when running an application by using Start -> Run.
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\\"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With