user19968266
user19968266

Reputation: 1

How do I access an argparse parameter with a space from a namespace?

import argparse
from signal import default_int_handler

parser = argparse.ArgumentParser(description = "Parse arguments into client file", formatter_class = argparse.ArgumentDefaultsHelpFormatter)

parser.add_argument('-p port', nargs = '?', default = 27993, type = int)
parser.add_argument('-s', nargs = '?', default = False)
parser.add_argument('hostname')


args = parser.parse_args()


print(args.p_port)

In something like this, when I try to access the p_port argument, I get an error:

AttributeError: 'Namespace' object has no attribute '_p_port'

Upvotes: 0

Views: 96

Answers (1)

Ture Pålsson
Ture Pålsson

Reputation: 6776

Traditionally,

  1. a single dash is used for single-letter flags,

  2. a double dash is used for flags with multi-letter names, and

  3. flags never have spaces in them.

(1) and (2) are quite frequently broken, but breaking (3) is going to cause you no end of headaches. I strongly recommend that you make that parameter name --p-port or --p_port.

Upvotes: 2

Related Questions