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 将结束的\"
解释为逐字"
(虽然不提示关闭未转义"
- 即具有语法函数的 - 那么>缺少)。
- 虽然 PowerShell (Core) 7+ 现在确实在幕后执行此操作,但 Windows PowerShell不 :它放置
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/