Reading named command arguments

Can I use argparse to read command line arguments that should not be in a specific order? I looked through the documentation , but most of them focused on displaying the content based on the provided arguments (e.g. --h ).

My script is currently reading ordered, unnamed arguments:

myscript.py foo-val bar-val

using sys.argv :

 foo = sys.argv[1] bar = sys.argv[2] 

But I would like to change the input so that it is invalid by name:

myscript.py --bar = bar-val --foo = foo-val

+7
python arguments
source share
2 answers

You can use Optional arguments as follows:

 import argparse, sys parser=argparse.ArgumentParser() parser.add_argument('--bar', help='Do the bar option') parser.add_argument('--foo', help='Foo the program') args=parser.parse_args() print args print sys 

Then, if you call it with ./prog --bar=bar-val --foo foo-val , it prints:

 Namespace(bar='bar-val', foo='foo-val') ['Untitled 14.py', '--bar=bar-val', '--foo', 'foo-val'] 

Or, if the user wants help to be created using argparse too:

  $ ./prog -h usage: Untitled 14.py [-h] [--bar BAR] [--foo FOO] optional arguments: -h, --help show this help message and exit --bar BAR Do the bar option --foo FOO Foo the program 
+4
source share

The answer is yes . A quick response to the documentation argparse would also respond.

Here is a very simple example: argparse is capable of handling much more specific needs.

 import argparse parser = argparse.ArgumentParser() parser.add_argument('--foo', '-f', help="a random options", type= str) parser.add_argument('--bar', '-b', help="a more random option", type= int, default= 0) print(parser.format_help()) # usage: test_args_4.py [-h] [--foo FOO] [--bar BAR] # # optional arguments: # -h, --help show this help message and exit # --foo FOO, -f FOO a random options # --bar BAR, -b BAR a more random option args = parser.parse_args("--foo pouet".split()) print(args) # Namespace(bar=0, foo='pouet') print(args.foo) # pouet print(args.bar) # 0 

Off-course, in a real script, you will not hard-code command-line options and instead call parser.parse_args() (without an argument). It will force argparse to take the sys.args list as command line arguments.

You can call this script as follows:

 test_args_4.py -h # prints the help message test_args_4.py -f pouet # foo="pouet", bar=0 (default value) test_args_4.py -b 42 # foo=None, bar=42 test_args_4.py -b 77 -f knock # foo="knock", bar=77 

You will discover many other functions by reading the document;)

+2
source share

All Articles