Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop argparse from globbing filepath

I am using python argparse with the following argument definition:

parser.add_argument('path', nargs=1, help='File path to process')

But when I enter my command with a wildcard argument, argparse globs all the file paths and terminates with an error.

How do I get argparse not to glob the files?

like image 600
jldupont Avatar asked Sep 09 '11 19:09

jldupont


People also ask

How do you make Argparse optional?

Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser.

What does Nargs do in Argparse?

By default, argparse will look for a single argument, shown above in the filename example. If you want your parameters to accept a list of items you can specify nargs=n for how many arguments to accept. Note, if you set nargs=1 , it will return as a list not a single value.

What is parser Add_argument in Python?

parser. add_argument('indir', type=str, help='Input dir for videos') created a positional argument. For positional arguments to a Python function, the order matters. The first value passed from the command line becomes the first positional argument. The second value passed becomes the second positional argument.

What is Store_true in Python?

The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present. The source for this behavior is succinct and clear: http://hg.python.org/cpython/file/2.7/Lib/argparse.py#l861.


2 Answers

The shell is expanding the wildcard argument before argparse gets a chance to see it. Put quotes around the wildcard argument to prevent the shell from expanding it.

You could later perform the wildcard expansion with glob.glob.

like image 73
unutbu Avatar answered Sep 28 '22 04:09

unutbu


How do I get argparse not to glob the files?

You don't.

You get the shell to stop globbing.

However. Let's think for a moment.

You're saying this in your code

parser.add_argument('path', nargs=1, help='File path to process')

But you are actually providing wild-cards when you run it.

One of those two is wrong. Either stop providing wild-cards at run time or fix argparse to allow multiple filenames.

like image 30
S.Lott Avatar answered Sep 28 '22 06:09

S.Lott