Reputation: 31
I need to pass an '&' character to a script, running from Windows cmd.exe. Do you know how to escape it? Carets are used in cmd.exe for general escaping.
x:\abc>python args.py "hello world!" "" ^& end
args.py
hello world!
^&
end
x:\abc>python args.py "hello world!" "" "&" end
args.py
hello world!
^&
end
import sys
for i in sys.argv:
print i
I have a C program: a.exe that is printing from argv, it seems to get the arguments correctly
x:\abc>a.exe "hello world!" "" "&" end
or
x:\abc>a.exe "hello world!" "" ^& end
produces
a.exe
hello world!
&
end
What's going on here, any ideas?
Upvotes: 2
Views: 1683
Reputation: 22483
I can't answer why Python on Windows is doing this, but this kind of issue ("this language, running on this platform, in these versions... does something wrong/different/weird") is pretty common.
A lot of my code that run across different language versions and platforms has at least a little "where am I running?" interrogation and a few shims to "make things right." Externalizing the handling of those special cases from your main logic helps to keep programs simple. So you might handle this problem with this kind of shim:
import platform
import sys
_WINDOWS = platform.system() == "Windows"
def strip_excess_caret(s):
return s[1:] if s.startswith("^") else s
def clean_argv():
if _WINDOWS:
return [ strip_excess_caret(a) for a in sys.argv ]
else:
return sys.argv
for arg in clean_argv():
print arg
Upvotes: 1