python – Process arguments from a command line

Question:

Hi, I'm trying to work with command line arguments process, I'm going to show you an example command line I'm using:

user@notebook$ python arquivo.py -nome Lucas --idade 12 --pais Brasil

Code:

import sys
import argparse


def main():
    parser = argparse.ArgumentParser(description='Descricao')
    parser.add_argument('-nome', required=True)
    parser.add_argument('--idade', required=True)
    parser.add_argument('--pais', required=True)
    
    args = parser.parse_args()

    print("Nome = {}".format(args.nome))
    print("Idade = {}".format(args.idade))
    print("País = {}".format(args.pais))

    return 0


if __name__ == '__main__':
    sys.exit(main())

Exit:

Nome = Lucas
Idade = 12
País = Brasil

I would like to know if there is the possibility of receiving, for example the age without having to use the –age in the command line, like this:

user@notebook$ python arquivo.py -nome Lucas 12 --pais Brasil

Therefore, I would like the output to remain:

Nome = Lucas
Idade = 12
País = Brasil

Answer:

Just inform that "age" is a positional argument, removing the hyphens and leaving only the name:

parser.add_argument('idade', type=int) # retire o "--"

I also include the type , indicating that it must be an integer (so it will already validate, returning an error if no number is provided).

So, you can call in any of the 3 ways below:

python arquivo.py 12 -nome Lucas --pais Brasil
python arquivo.py -nome Lucas 12 --pais Brasil
python arquivo.py -nome Lucas --pais Brasil 12

In this case, "age" will be the first argument that is not in the --nome valor format, so the above three options work. It also doesn't need required , as it will be mandatory by default.

For more details, see the add_argument documentation .

Scroll to Top