Handle spaces in argparse input

為{幸葍}努か 提交于 2019-12-30 01:36:12

问题


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

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)


回答1:


For those who can't parse arguments and still get "error: unrecognized arguments:" I found a workaround:

parser.add_argument('-d', '--dmp', nargs='+', ...)
opts = parser.parse_args()

and then when you want to use it just do

' '.join(opts.dmp)



回答2:


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.




回答3:


Bumped into this problem today too.

-d "foo bar"

didn't help. I had to add the equal sign

-d="foo bar"

and then it did work.




回答4:


After some experiments (python 2.7 Win10) I found out that the golden rule is to put quotes ("") around arguments which contain spaces and do NOT put if there are no spaces in argument. Even if you are passing a string/path. Also putting a single quotes ('') is a bad idea, at least for Windows.

Small example: python script.py --path ....\Some_Folder\ --string "Here goes a string"



来源:https://stackoverflow.com/questions/18157376/handle-spaces-in-argparse-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!