【问题标题】:double quotes and whitespace as argument to python script in PowerShell双引号和空格作为PowerShell中python脚本的参数
【发布时间】:2018-08-17 17:37:16
【问题描述】:

我正在尝试使用 PowerShell 运行 python 脚本。在该 python 脚本中,我尝试使用包含双引号和空格的命令行参数,但无法正常工作。我怀疑这是 PowerShell 的问题。

(简化的)python 脚本如下所示:

import sys
print(sys.argv[1])

以下调用和输出显示了问题

python script.py --arg=foo
--arg=foo

python script.py --arg='\"foo\"'
--arg="foo"

python script.py --arg='\"fo o\"'
--arg="fo

但我最终需要的是

--arg="fo o"

它会去掉空格之后的所有内容。我在它工作的 Linux bash 中测试了相同的脚本(在 foo 周围有双引号)。这似乎不是 python 问题,而是 PowerShell 问题,有人可以帮助我吗?最后我想要一个完整的 JSON-String 作为参数。

【问题讨论】:

  • 你试过用\转义空格吗?
  • 是的。然后我得到 --arg="fo\
  • PowerShell 版本?操作系统?
  • 好的,我找到了一种方法:python .\script.py '--arg="""fo o"""' 我得到--arg="fo o"。不过实话说。微软。重量...?
  • 或者python .\script.py '"--arg=\"fo o\""'。最外面的一组引号将令牌定义为 PowerShell 的字符串。外部双引号集用于将带有内部(转义)双引号的整个标记传递给 Python 进程。话虽如此,您为什么要尝试传递这样的参数而不是使用argparse

标签: python json powershell command-line-interface


【解决方案1】:

9 个月没有答案。当前的解决方法是使用\" 转义"

这是错误:https://github.com/PowerShell/PowerShell/issues/1995

【讨论】:

  • 你应该得到一枚奖牌
  • 谢谢先生!!!我的天啊,我一直在寻找这个
【解决方案2】:

用'\`'(反斜杠+反引号)转义"也可以(我不能在代码样式的降价中包含反引号,因为我不知道如何转义它......讽刺)。

请注意,带有转义双引号的整个参数也必须封装在双引号中。在它周围加上单引号是行不通的。

来源:http://www.rlmueller.net/PowerShellEscape.htm

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    • 2015-10-29
    • 2020-04-06
    • 2019-07-19
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多