Process command line arguments

Asked

Viewed 53 times

3

Hello, I’m trying to work with command line argument process, I’ll 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 a possibility of receiving, for example age without having to use the --age on the command line, so:

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

So I’d like the exit to stay:

Nome = Lucas
Idade = 12
País = Brasil
  • What happens if you take the -- of --idade in the add_argument?

  • By the way, why to display the name you put args.arquivo? For age you put args.nome?

  • Pardon friend, typo, in the question of the name "file"

  • In relation to - and -- it’s just a pattern I want to adopt, but it wouldn’t be necessary

2 answers

5


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 included 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 it 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 not in the format --nome valor, so the three options above work. And also no need to required, because by default it will already be mandatory.

For more details, see documentation of add_argument.

5

As the documentation cites, the fact that you remove the hyphens from the argument name makes it a positional argument of your command and thus do not need to inform the name (read more about POSIX to understand the pattern).

So instead of:

parser.add_argument('--idade', required=True)

Do:

parser.add_argument('idade', type=int)

So you can execute the command -nome Lucas 12 --pais Brasil successfully.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.