python - 将特殊字符传递给 cmd.exe 中的 python 脚本

标签 python windows cmd command-line-arguments

我需要将“&”字符传递给从 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

参数.py

import sys
for i in sys.argv:
       print i

我有一个 C 程序:从 argv 打印的 a.exe,它似乎正确地获取了参数

用a.exe

x:\abc>a.exe "hello world!" "" "&" end
or
x:\abc>a.exe "hello world!" "" ^& end

产生

a.exe
hello world!

&
end

这是怎么回事,有什么想法吗?

最佳答案

我无法回答 为什么 Windows 上的 Python 正在这样做,但是这种问题(“这种语言,在这个平台上运行,在这些版本中......做错了什么/不同的/很奇怪”)很常见。

我的许多跨不同语言版本和平台运行的代码至少有一点“我在哪里运行?”审讯和一些shims “把事情做好”。从您的主要逻辑中外部化这些特殊情况的处理有助于保持程序简单。所以你可以用这种 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

关于python - 将特殊字符传递给 cmd.exe 中的 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25211353/

相关文章:

python - 在运行时创建一个 python 函数来匹配可变数量的字典条目

python - 如何使用 Python 列出目录

windows - 从 CMD 检测命令行应用程序,而不会弄乱 PATH 变量或 System32/SysWow64 目录

string - 替换文本文件中的单个字符时出现意外结果

batch-file - 在批处理脚本中对标签使用 CALL

python - 将 Spark 与 Flask 和 JDBC 一起使用

python - 使用 Scipy 在任意点插入和评估 numpy 数组的问题

python - tkinter 消息框未显示在 Windows 任务栏上

java - java和ntdll.dll之间的关系

c# - .NET WinForms 应用程序的 MVC/MVP 框架