2016-08-11 8 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' 

私はこれを入力したいので、私はこのようにそれを持っている理由は次のとおりです。私は本当に私がやっているか知っているかいただきました!間違った私が見カント...ここ

は私の誤りではいけないのどちらかゲームを始めることなく端末で実行できるので、単にpython3と入力するとadventure.pyが起動します。しかし、私はそれを今でも行うことはできません:P。 python3のadventure.py -cとpython3のアドベンチャーだけが動作します。

誰にも解決策がありますか?

ありがとうございました。

答えて

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:に置き換えます。