AttributeError:“命名空间”对象没有属性“rmvApp”

2024-06-26 14:48:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试向脚本中添加两个选项“add”和“rmv”,但使用add选项时出现以下错误:

回溯(最近一次呼叫最后一次): 文件“/home/bsony/bin/moveVM”,第240行,在 elif(参数rmvApp): AttributeError:“命名空间”对象没有属性“rmvApp”

反之亦然,当我使用rmv选项时,会出现以下错误:

回溯(最近一次呼叫最后一次): 文件“/home/bsony/bin/moveVM”,第238行,在 如果(args.addApp): AttributeError:“命名空间”对象没有属性“addApp”

截取的相关代码如下:

#Set main parser
parser = argparse.ArgumentParser(description='A scirpt to add, move or remove     apps file the various apps file')
sub_parser = parser.add_subparsers(dest='command')

#Set add parser
addApp = sub_parser.add_parser('add', help='Add new app to apps file')
addApp.add_argument('-a', '--add', dest='addApp', type=str, help='The application you want to add to the apps file')

#Set remove parser
rmvApp = sub_parser.add_parser('rmv', help='Remove app from apps file')
rmvApp.add_argument('-r', '--rmv', dest='rmvApp', type=str, help='The application you want to remove from the apps file')

args = parser.parse_args()

#Dictionary to store variables making it easier to pass between functions
appDict = {
    "environment": "",
    "appToAdd": "",
    "appToRmv": "",
    "appToMove": "",
    "realEnv": "",
    "newHost": "",
    "newVMID": "",
    "oldAppLine": "",
    "newAppLine": "",
    "oldPRLines": []
}

appsFileList = [] #empty list to ingest apps file to

#Get evironment name for apps file
appDict["environment"] = raw_input('What environment would you like to move an app from? (dev, pt, pr): ').lower()

if (appDict["environment"] not in ["dev", "ppe", "pt", "pr"]):
    print("\nYou did not enter a valid environment...exiting...")
    exit()

#Set apps file location
userID = getpass.getuser() #gets linux user ID to use in appsFilePath

#check for add or remove flags and call function if flags are used
if (args.addApp):
    addApp(appsFileList, appDict, appsFilePath, userID)

if(args.rmvApp):
    rmvApp(appsFileList, appDict)

Tags: appstoaddparserifenvironmenthelpargs
1条回答
网友
1楼 · 发布于 2024-06-26 14:48:43

您需要先查看指定了哪个命令,然后才能访问特定于命令的参数。所以你可以做:

if args.command == 'add':
    print(args.addApp)
elif args.command == 'rmv':
    print(args.rmvApp)
else:
    print("No command specified")

只有指定命令的子解析器参数才会出现

相关问题 更多 >