Python argparse 无法正确处理 Windows 中的路径

标签 python powershell argparse

Python 中的 argparse 库不适用于路径,包含空格和末尾的“\”(反斜杠)。 argparse 中的解析器将路径末尾的反斜杠解析为“(双引号)。

下面的代码是具有相同问题的示例。

import argparse


if __name__=="__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-w', '--weight', type=str)

    args = parser.parse_args()

    print(args.weight_path)

例如在 PowerShell 中,

PS > python sample.py -w ".\test test\"
.\test test"

它确实适用于不包含空格的路径。

PS > python sample.py -w ".\testtest\"
.\test test\
PS > python sample.py -w "testtest\"
test test\
PS > python sample.py -w "testtest"
test test

在 PowerShell 中使用 argparse 有什么问题吗?

我什至不知道如何搜索这个问题...

最佳答案

您看到的是 Windows PowerShell 中的错误,该错误已在 PowerShell (Core) 7+更正。 :

  • 到PowerShell,基于它自己的语法string literals ,字符串 ".\test test\" 的逐字值为 .\test test\,因为 \ 没有在PowerShell中的特殊含义(PowerShell的转义字符是`,即所谓的反引号)。

  • 但是,基于 most widely used conventions for parsing a process command line on Windows ,在调用外部程序时,此字符串必须作为 ".\test test\\" 放置在幕后构造的进程命令行上,考虑到进程应该将 \" 解析为 转义 " 字符。

    • 虽然 PowerShell (Core) 7+ 现在确实在幕后执行此操作,但 Windows PowerShell :它放置 ".\test test\",这会导致 Python 将结束的 \" 解释为逐字 " (虽然提示关闭未转义 " - 即具有语法函数的 - 那么>缺少)。

Windows PowerShell 的解决方法手动\ 字符加倍。结束前":

# Windows PowerShell only: double the \ before the closing "
python sample.py -w ".\test test\\"

顺便说一句:虽然PowerShell(核心)7+已经修复了这个特定问题,但故意 在传递给外部程序的参数中嵌入 " 字符 - 请参阅 this answer

关于Python argparse 无法正确处理 Windows 中的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75527560/

相关文章:

python - pyside连接错误 "RuntimeError: Failed to connect signal clicked()"

function - 如何更有效地编写此Powershell函数?

azure - 使用逻辑应用创建具有关键字 "Keyword2"和 "Keyword2"的新 AD 组时配置警报

powershell - 在脚本 block 调用中设置$ _

Python argparse 整数条件 (>=12)

python - Django - 根据用户组过滤下拉选项

c# - 模拟网络浏览器

python - 如何检查Python中是否存在方法?

Python argparse 如果不是 int 则跳过

python - 使用 argparse 输出调用函数