我试图在脚本中添加2个选项“ add”和“ rmv”,但是当我使用add选项时出现此错误:
回溯(最近通话最近): 文件“ / home / bsony / bin / moveVM”,第240行,在 elif(args.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)
答案 0 :(得分:0)
在访问特定于命令的参数之前,需要查看指定了哪个命令。因此,您可以这样做:
if args.command == 'add':
print(args.addApp)
elif args.command == 'rmv':
print(args.rmvApp)
else:
print("No command specified")
仅会显示指定命令的子解析器参数。