Python ArgumentParser: Create and Parse Command Line Arguments – Python Tutorial

By | January 9, 2023

In order to use command line arguments in python, we can use sys package. For example:

Python Use Command Line Arguments: A Beginner Guide – Python Tutorial

However, we also can use python ArgumentParser package. In this tutorial, we will introduce how to use ArgumentParser to create and parse these command line arguments.

How to create command line arguments using ArgumentParser.

It is easy to create arguments using ArgumentParser library. Here is an example:

from argparse import ArgumentParser
if __name__ == '__main__':
    parser = ArgumentParser()
    # create argument
    parser.add_argument('--embedding_file', type=str, default='data/yelp13/embedding-skip.txt')
    parser.add_argument('--embedding_dim', type=int, default=200) 
    parser.add_argument('--dim', type=int, default=200) 
    parser.add_argument('--hidden_size', type=int, default=100) 

    parser.add_argument('--batch_size', type=int, default=4)
    parser.add_argument('--num_workers', type=int, default=1) 

    parser.add_argument('--class_num', type=int, default=5) 
    parser.add_argument('--lr', type=float, default=0.005)
    parser.add_argument('--lr_decay', type=float, default=0.97)

    args = parser.parse_args()

    print(type(args))
    print(args)

Here we have created some command line arguments for our python script. We also can find that we can add a command line argument as follows:

parser.add_argument('--embedding_dim', type=int, default=200)

–embedding_dim: the command line argument name.

type: the argument data type, it can be int, float, str et al.

default: the default value of this argument.

Run code above, we will get:

<class 'argparse.Namespace'>
Namespace(batch_size=4, class_num=5, dim=200, embedding_dim=200, embedding_file='data/yelp13/embedding-skip.txt', hidden_size=100, lr=0.005, lr_decay=0.97, num_workers=1)

We can find:

args is argparse.Namespace

How to get command line argument?

It is easy to get our command line argument by args. Here is an example:

print(type(args.dim), args.dim)

We can use args.argument_name to get one command line argument. Run code above, we will find:

<class 'int'> 200

If you want to add new argument, you can do as follows:

args.lamda = 30.0
print(args)
print(type(args.lamda), args.lamda)

As to lamda argument, we have not added it by parser.add_argument() function. However, we also can use args.argument_name to get or modify its value.

<class 'float'> 30.0

Moreover, look at example below:

args.dim = "/model/"
print(type(args.dim), args.dim)

We can find args.dim is int from the code above, however, we also can modify its value and data type easily.

Run this code, we will see:

<class 'str'> /model/

Here args.dim is python string.