Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle spaces in argparse input

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)

like image 217
ofer.sheffer Avatar asked Aug 10 '13 00:08

ofer.sheffer


1 Answers

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) 
like image 164
Illarion Kovalchuk Avatar answered Oct 31 '22 20:10

Illarion Kovalchuk