2016-08-11 99 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: