处理argparse输入中的空格

处理argparse输入中的空格

本文介绍了处理argparse输入中的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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"

注意:参数周围带有".

NOTICE: argument has "" around it.

这篇关于处理argparse输入中的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 22:45