【发布时间】: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