code4fun code4fun - 8 months ago 45
Python Question

Python argparse to a game

I'm trying to figure out argparse for my adventure game.
This is my code:

parser = argparse.ArgumentParser(description='Adventure')
parser.add_argument('--cheat','-c', action='store_true', help='cheat')
parser.add_argument('--info','-i', action='store_true', help='Information' )
parser.add_argument('--version','-v', action='store_true', help='Version' )
parser.add_argument('--about', '-a', action='store_true', help='About' )

args = parser.parse_args()

if args.cheat or args.c:
elif or args.i:
elif args.version or args.v:
elif args.about or args.a:
#Game code#

But I'm getting an error when I have all these arguments. It worked fine when I only had cheat to begin with but when I added all the others, it messed up. Either I dont really know what i'm doing or I cant see whats wrong...

Here is my error:

$ python3 --info
Traceback (most recent call last):
File "", line 12, in <module>
if args.cheat or args.c:
AttributeError: 'Namespace' object has no attribute 'c'

The reason I have it like this is because I want to type in this in terminal without starting the game, so if you just type python3 the game will start. But I cant even do that now :P.
Only python3 -c and python3 adventure --cheat works.

Anyone know a solution to this?



The error messages is pretty clear: 'Namespace' object has no attribute 'c'.

argparse library automatically determines the name of the attribute to store the value of the command line option in the following way:

For optional argument actions, the value of dest is normally inferred from the option strings. ArgumentParser generates the value of dest by taking the first long option string and stripping away the initial -- string. If no long option strings were supplied, dest will be derived from the first short option string by stripping the initial - character.

Since you have both long and short names for your option, the long name is used. In other words, replace if args.cheat or args.c: with if args.cheat:.