我需要通过'&'脚本的字符,从Windows cmd.exe运行。你知道怎么逃避吗?在cmd.exe中使用插入符号进行一般转义。
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
我有一个C程序:从argv打印的a.exe,它似乎正确地获取了参数
x:\abc>a.exe "hello world!" "" "&" end
or
x:\abc>a.exe "hello world!" "" ^& end
生成
a.exe
hello world!
&
end
这里发生了什么,有什么想法吗?
答案 0 :(得分:1)
我无法回答为什么 Windows上的Python正在这样做,但是这种问题(“这种语言,在这个平台上运行,在这些版本中......做错了/不同/奇怪的“)很常见。
我的很多代码在不同的语言版本和平台上运行至少有一点“我在哪里运行?”审讯和一些shims“使事情正确”。从主逻辑中外部处理这些特殊情况有助于简化程序。所以你可以用这种垫片处理这个问题:
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