2016-08-11 103 views
1

我想弄清楚我的冒险游戏的argparse。 这是我的代码:Python argparse游戏

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: 
    print("Cheat") 
    sys.exit() 
elif args.info or args.i: 
    print("Information") 
    sys.exit() 
elif args.version or args.v: 
    print("Version") 
    sys.exit() 
elif args.about or args.a: 
    print("About") 
    sys.exit() 
else: 
    #Game code# 

但我发现了一个错误,当我把所有这些论点。如果我只是从头开始欺骗,但是当我添加所有其他人时,它运行良好,它搞砸了。要么我真的不知道我在做什么,或者我不能看到什么错......

这是我的错误:

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

我之所以像这样,是因为我需要输入这个在没有开始游戏的终端中,所以如果你只是输入p​​ython3 adventure.py游戏就会开始。但我现在甚至不能这样做:P。 只有python3 adventure.py -c和python3冒险--cheat工程。

任何人都知道这个解决方案吗?

谢谢。

回答

2

错误消息非常明确:'Namespace' object has no attribute 'c'

​​库自动确定属性的名称来存储命令行选项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.

既然你有你的选择多空双方的名称,使用长名称。换句话说,将if args.cheat or args.c:替换为if args.cheat: