处理 argparse 输入中的空格 [英] Handle spaces in argparse input
问题描述
使用 python 和 argparse,用户可以输入带有 -d 作为标志的文件名.
Using python and argparse, the user could input a file name with -d as the flag.
parser.add_argument("-d", "--dmp", default=None)
但是,当路径包含空格时,这会失败.例如.
However, this failed when the path included spaces. E.g.
-d C:\SMTHNG\Name with spaces\MORE\file.csv
注意:空格会导致错误(标志只接受 'C:SMTHNG\Name' 作为输入).
NOTE: the spaces would cause an error (flag only takes in 'C:SMTHNG\Name' as input).
error: unrecognized arguments: with spaces\MORE\file.csv
我花了很长时间才找到这个问题的解决方案......(没有找到问答,所以我自己发帖)
Took me longer than it should have to find the solution to this problem... (did not find a Q&A for it so I'm making my own post)
推荐答案
简单的解决方案:argparse 将空格填充的字符串视为单个参数,如果它用引号括起来.
Simple solution: argparse considers a space filled string as a single argument if it is encapsulated by quotation marks.
此输入有效并解决"了问题:
This input worked and "solved" the problem:
-d "C:\SMTHNG\Name with spaces\MORE\file.csv"
注意:参数周围有".
这篇关于处理 argparse 输入中的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!