在cmd.exe中传递特定字符给python脚本
我需要在Windows的命令提示符(cmd.exe)中传递一个'&'字符给一个脚本。你知道怎么处理这个字符吗?在cmd.exe中,通常使用插入符号(^)来进行转义。
尝试 1
x:\abc>python args.py "hello world!" "" ^& end
args.py
hello world!
^&
end
尝试 2
x:\abc>python args.py "hello world!" "" "&" end
args.py
hello world!
^&
end
args.py
import sys
for i in sys.argv:
print i
我有一个C语言程序:a.exe,它从argv中打印内容,似乎能够正确获取参数。
使用 a.exe
x:\abc>a.exe "hello world!" "" "&" end
or
x:\abc>a.exe "hello world!" "" ^& end
产生了
a.exe
hello world!
&
end
这里发生了什么,有什么想法吗?
1 个回答
1
我不能确切说为什么在Windows上使用Python会出现这种情况,但这种问题(“这个语言,在这个平台上,使用这些版本……做了一些错误/不同/奇怪的事情”)是很常见的。
我写的很多代码在不同的语言版本和平台上运行时,都会有一些“我现在在哪儿运行?”的检查,还有一些适配层来“纠正问题”。把这些特殊情况的处理从主要逻辑中分离出来,可以让程序保持简单。所以你可以用这种适配层来解决这个问题:
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