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
Related
I have a Python script that can deploy some software in three different environments, let's call them development, testing and production. In order to select which environment the script should work with, I want to use mutually exclusive flags, like so:
./deploy.py --development
./deploy.py --testing
./deploy.py --production
So far I have this:
parser = argparse.ArgumentParser(description="Manage deployment")
group = parser.add_mutually_exclusive_group()
group.add_argument("-d", "--development", action='store_true', required=False)
group.add_argument("-t", "--testing", action='store_true', required=False)
group.add_argument("-p", "--production", action='store_true', required=False)
args = parser.parse_args()
Thing is, I want to have the environment in a single variable, so I can easily check it, instead of having to manually check args.development, args.testing and args.production.
Is there a way of having a common variable that the three arguments could write to so I could do something like args.environment?
Instead of using action='store_true', you can use action='store_const', assign an individual const value for each argument and the dest option of add_argument, so that all the arguments in the mutually exclusive group have the same destination in the object returned by parse_args.
parser = argparse.ArgumentParser(description="Manage deployment")
group = parser.add_mutually_exclusive_group()
group.add_argument("-d", "--development", action='store_const', dest='environment', const='development', required=False)
group.add_argument("-t", "--testing", action='store_const', dest='environment', const='testing', required=False)
group.add_argument("-p", "--production", action='store_const', dest='environment', const='production', required=False)
args = parser.parse_args()
print(args)
The output is:
$ ./test_args.py --production
Namespace(environment='production')
Instead of 3 arguments, you can just use one with choices:
parser = argparse.ArgumentParser(description="Manage deployment")
parser.add_argument("environment", choices=['development', 'testing', 'production'])
args = parser.parse_args()
print(args)
Examples:
>>> test_args.py
usage: concept.py [-h] {development,testing,production}
test_args.py: error: the following arguments are required: environment
>>> test_args.py testing
Namespace(environment='testing')
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
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
I have tons of variables and argument definitions. Is there a way to make this take up less lines, or am I stuck with it?
# Standard input module to absorb commands from CLI
parser = argparse.ArgumentParser(description='User inputs source and destination tables to transfer data.')
parser.add_argument('src_table', help='Source table not supplied.', type=str)
parser.add_argument('dest_table', help='Destination table not supplied.', nargs='?', type=str) # optional arg
parser.add_argument('instance_object', help='New item not supplied.', nargs='?', type=str)
parser.add_argument('instance_id', help='Item ID not supplied.', nargs='?', type=int)
args = parser.parse_args()
src_table = args.src_table
dest_table = args.dest_table
Resist the urge to create tons of variables. Access the values through args instead.
However, it is possible to convert all the attributes of args into global variables:
globals().update(**vars(args))
but this pollutes the global namespace.
A better option is to pass the args to a function:
def main(src_table, dest_table, instance_object, instance_id):
print(src_table, dest_table, instance_object, instance_id)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='User inputs source and destination tables to transfer data.')
parser.add_argument('src_table', help='Source table not supplied.', type=str)
parser.add_argument('dest_table', help='Destination table not supplied.', nargs='?', type=str) # optional arg
parser.add_argument('instance_object', help='New item not supplied.', nargs='?', type=str)
parser.add_argument('instance_id', help='Item ID not supplied.', nargs='?', type=int)
args = parser.parse_args()
main(**vars(args))
Thus, inside of main, all of arg's attributes will be accessible as local variables. Structuring your program this way allows your code to be used as both a script and be importable as a module. This makes your code more versatile, and is thus much nicer than "polluting" the global namespace with lots of variables.
write a script that takes two optional boolean arguments,"--verbose‚" and ‚"--live", and two required string arguments, "base"and "pattern". Please set up the command line processing using argparse.
This is the code I have so far for the question, I know I am getting close but something is not quite right. Any help is much appreciated.Thanks for all the quick useful feedback.
def main():
import argparse
parser = argparse.ArgumentParser(description='')
parser.add_argument('base', type=str)
parser.add_arguemnt('--verbose', action='store_true')
parser.add_argument('pattern', type=str)
parser.add_arguemnt('--live', action='store_true')
args = parser.parse_args()
print(args.base(args.pattern))
The string arguments are not required by default, so you need to state that. Also the print statement that uses the arguments is incorrect.
#!/usr/bin/python
import argparse
if __name__=="__main__":
parser = argparse.ArgumentParser(description='eg $python myargs.py --base arg1 --pattern arg2 [--verbose] [--live]')
parser.add_argument('--base', required=True, type=str)
parser.add_argument('--pattern', required=True, type=str)
parser.add_argument('--verbose', action='store_true')
parser.add_argument('--live', action='store_true')
args = parser.parse_args()
print "args.base=" + str(args.base)
print "args.pattern=" + str(args.pattern)
print "args.verbose=" + str(args.verbose)
print "args.live=" + str(args.live)
the #!/usr/bin/python at the top enables the script to be called directly, though python must be located there (to confirm, type $which python), and you must set the file to have execute permission ($chmod +x myargs.py)