Azure - Python - parse arguments from command line - python

community,
I am trying to parse arguments as default values for principal credentials on Azure using Python CLI. In my code, I am trying to hardcode the default values for the "--azure-client-id", "--azure-secret", "--azure-tenant" and "--azure-subscription-id" as default but I am not 100% how to add it. I have been searching all over the net but can't find the answer as yet
I am still learning and I was hoping that someone could help me.
Thank you in advances for your help
My code below
def parse_args(args):
'''parse arguments from command line'''
variables = {}
parser = argparse.ArgumentParser()
parser.add_argument("action",
help="the command to be action",
choices=["delete", "create"],
nargs='?',
default="set")
parser.add_argument("-f", "--folder",
dest="folder",
nargs='?',
help="folder container ARM template & parameters json",
metavar="FOLDER")
parser.add_argument("-b",
"--build-number",
dest="build_number",
help="build number of the resource number")
parser.add_argument("-c",
"--azure-client-id",
dest="azure_client_id",
help="azure client id")
parser.add_argument("-s",
"--azure-secret",
dest="azure_secret",
help="azure secret")
parser.add_argument("-t",
"--azure-tenant",
dest="azure_tenant",
help="azure tenant")
parser.add_argument("-sid",
"--azure-subscription-id",
dest="azure_subscription_id",
help="azure subscription id")
args = parser.parse_args(args)

parser.add_argument('--azure-client-id', nargs='?', const='ID',
default='ID')
nargs='?' = 0 or 1 arguments
const='ID' = sets default value when no arguments are passed
default='ID' = if '--azure-client-id' is not specified this will be the default value
https://docs.python.org/3/library/argparse.html#nargs

Related

python argparse default with nargs wont work [duplicate]

This question already has answers here:
Argparse optional argument with different default if specified without a value
(2 answers)
Closed last month.
Here is my code:
from argparse import ArgumentParser, RawTextHelpFormatter
example_text = "test"
parser = ArgumentParser(description='my script.',
epilog=example_text,
formatter_class=RawTextHelpFormatter)
parser.add_argument('host', type=str, default="10.10.10.10",
help="Device IP address or Hostname.")
parser.add_argument('-j','--json_output', type=str, default="s", nargs='?',choices=["s", "l"],
help="Print GET statement in json form.")
#mutally exclusive required settings supplying the key
settingsgroup = parser.add_mutually_exclusive_group(required=True)
settingsgroup.add_argument('-k', '--key', type=str,
help="the api-key to use. WARNING take care when using this, the key specified will be in the user's history.")
settingsgroup.add_argument('--config', type=str,
help="yaml config file. All parameters can be placed in the yaml file. Parameters provided from form command line will take priority.")
args = parser.parse_args()
print(args.json_output)
my output:
None
Everything I am reading online says this should work, but it doesn't. Why?
You could use the const= parameter. const stores its value when the option is present but have no values
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-j', '--json-output', nargs='?', choices=['s', 'l'], const='s')
args = parser.parse_args()
However design wise, it might be better to use the following:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output-type', choices=['json-s', 'json-l', 'normal'], default='normal')
args = parser.parse_args()

Store argparse input to use as variable

I am using argparse to require input from the user for a hardware id to then be called later on, I cannot work out how to get it so the user types
<command> --id <id>
Please help me see where I'm going wrong! Thanks
parser = argparse.ArgumentParser(description='Return a list of useful information after specifying a hardare/asset ID')
parser.add_argument('--id', type=str, required=True, help ='A hardware/asset id to provide information on')
args = vars(parser.parse_args())
args = parser.parse_args()
def main():
hardware_id = hardware_id_input
host = get_host_information(hardware_id)
print(host["hostname"])
print(host["hardware_id"])
Ditch the call to vars. You would have your argument stored as args.id after parsing. You would then call your main with the args.id as input.
Edit: added a code sample
def main(hw_id):
print(hw_id)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='Description.')
parser.add_argument('--id', type=str, help='The hardware id.', required=True)
args = parser.parse_args()
main(args.id)

Allow unknown arguments using argparse

I have a python script that requires the user to enter two arguments to run it, the arguments could be named anything.
I have also used argparse to allow the users to use a switch '-h' to get instructions of what is required to run the script.
The problem is that now I have used argparse I am getting an error when I pass my two randomly named arguments with the script.
import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-h', '--help', action='help',
help='To run this script please provide two arguments')
parser.parse_args()
currently when I run python test.py arg1 arg2 the error is
error: unrecognized arguments: arg1 arg2
I would like the code to allow the user to run test.py with a -h if required to see the instructions but also allow them to run the script with any two arguments as well.
Resolution with help tag to provide the user with context regarding the arguments required.
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-h', '--help', action='help', help='To run this script please provide two arguments: first argument should be your scorm package name, second argument should be your html file name. Note: Any current zipped folder in the run directory with the same scorm package name will be overwritten.')
parser.add_argument('package_name', action="store", help='Please provide your scorm package name as the first argument')
parser.add_argument('html_file_name', action="store", help='Please provide your html file name as the second argument')
parser.parse_args()
Try the following code :-
import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-h', '--help', action='help',
help='To run this script please provide two arguments')
parser.add_argument('arg1')
parser.add_argument('arg2')
args, unknown = parser.parse_known_args()
All your unknown arguments will be parsed in unknown and all known in args.
import argparse
parser = argparse.ArgumentParser(description='sample')
# Add mandatory arguments
parser.add_argument('arg1', action="store")
parser.add_argument('arg2', action="store")
# Parse the arguments
args = parser.parse_args()
# sample usage of args
print (float(args.arg1) + float(args.arg2))
You need to add those arguments to the parser:
parser.add_argument("--arg1", "-a1", dest='arg1', type=str)
parser.add_argument("--arg2","-a2", dest='arg2', type=str)
If those arguments don't have the param required=true, you will be able to call the program without this arguments, so you can run the program with only the -h flag. To run the program with the arguments:
python test.py --arg1 "Argument" --arg2 "Argument"
Then, to have the arguments in variables you have to read them:
args = parser.parse_args()
argument1=args.arg1
argument2=args.arg2

Python Argument Parser - the following arguments are reqired --name

When I run the following code:
def read_args():
parser = default_parser()
parser.add_argument('--tensorboard-dir', type=str, default='/tmp/cifar10/tensorboard')
parser.add_argument('-N', type=int, default=50000, help="Use N training examples.")
return parser.parse_args()
def main():
flags = readargs()
I have the following error output:
The following arguments are required: --name
However when I add the --name argument:
def read_args():
parser = default_parser()
parser.add_argument('--name', type=str, default='cifar10test')
parser.add_argument('--tensorboard-dir', type=str, default='/tmp/cifar10/tensorboard')
parser.add_argument('-N', type=int, default=50000, help="Use N training examples.")
return parser.parse_args()
def main():
flags = readargs()
is also creating problem.
Any ideas?
It appears that default_parser contains a --name argument which is required. What you're doing in your second example is defining the argument twice - once in default_parser and once in your program. Instead, you should be passing a --name argument when calling your program from the command line.
Example:
python cifar.py -N=1200 --tensorboard-dir=file.txt --name=cool_name
Alternatively, you could remove default_parser and construct your own ArgumentParser:
`parser = argparse.ArgumentParser()`
Full working demo:
import argparse
def read_args():
parser = argparse.ArgumentParser()
parser.add_argument('--tensorboard-dir', type=str,
default='/tmp/cifar10/tensorboard')
parser.add_argument('-N', type=int, default=50000,
help="Use N training examples.")
return parser.parse_args()
def main():
flags = vars(read_args())
# You can access your args as a dictionary
for key in flags:
print("{} is {}".format(key, flags[key]))
main()
The parser returns a Namespace object, but we can access its (much simpler) internal dictionary using vars(Namespace). You can then get your arguments by accessing the dictionary, for example, flags['N']. Note that tensorboard-dir becomes tensorboard_dir inside your python program to avoid issues with the subtraction operator.
Call it from the command line (I'm using Bash):
python cifar.py -N=1200 --tensorboard-dir=file.txt
Output:
tensorboard_dir is file.txt
N is 1200

How to pass a list of arguments to python command

parser = argparse.ArgumentParser(description='Run the app')
skill_list = utils.read_yaml_file('skill_list.yml')
parser.add_argument('skill', choices=skill_list, help="Which skill?")
parser.add_argument('endpoints', default=None, help="Configuration file for the connectors as a yml file")
skill = parser.parse_args().skill
endpoints = parser.parse_args().endpoints
In the above code, I can pass two parameters to as follows:
run.py joke endpoints.yml
If my 'skill' is a variable list, meaning that I don't know how much arguments users might pass. In such a case, I can do:
run.py joke command weather endpoints.yml
Here "joke command weather" will be passed by the 'skill' argument. How can I do that?
It is preferable to use -foo or --foo for your endpoints. But If u want exactly same passing order of arguments. This should work
parser.add_argument('skill', choices=skill_list, help="Which skill?", nargs='+')
parser.add_argument('endpoints', default=None, help="Configuration file for the connectors as a yml file")
You also need to provide nargs parameter in add_argument function.
parser.add_argument('--skill', nargs='+', help='List of skills', required=True)
parser.add_argument('--endpoints', default=None, help="Configuration file for the connectors as a yml file", required=True)
# Usage
# python run.py --skill joke command weather --endpoints endpoints.yml

Categories

Resources