argparse

Use dictionary for Python argparse

风流意气都作罢 提交于 2019-12-01 18:47:02
问题 I have a dictionary which maps human readable values to three different Python specific values. How can the argparse Python module use this dictionary to get me the specific values while the user can choice between the keys. Currently I have this: def parse(a): values = { "on": True, "off": False, "switch": None } parser = argparse.ArgumentParser() parser.add_argument("-v", "--value", choices=values, default=None) args = parser.parse_args(a) print("{}: {}".format(type(args.value), args.value)

Using unittest to test argparse - exit errors

南楼画角 提交于 2019-12-01 18:40:32
问题 Going off of Greg Haskin's answer in this question, I tried to make a unittest to check that argparse is giving the appropriate error when I pass it some args that are not present in the choices . However, unittest generates a false positive using the try/except statement below. In addition, when I make a test using just a with assertRaises statement, argparse forces the system exit and the program does not execute any more tests. I would like to be able to have a test for this, but maybe it

Add top level argparse arguments after subparser args

自作多情 提交于 2019-12-01 18:03:37
How can you allow for top-level program arguments to be added after using a subcommand from a subparser? I have a program that includes several subparsers to allow for subcommands, changing the behavior of the program. Here is an example of how its set up: #!/usr/bin/env python # -*- coding: utf-8 -*- import argparse def task_a(): print('did task_a') def task_c(): print('did task_c') def task_d(): print('did task_d') def run_foo(args): a_arg = args.a c_arg = args.c if a_arg: task_a() if c_arg: task_c() def run_bar(args): a_arg = args.a d_arg = args.d if a_arg: task_a() if d_arg: task_d() def

argparse conflict resolver for options in subcommands turns keyword argument into positional argument

不打扰是莪最后的温柔 提交于 2019-12-01 17:59:34
I have a Python script that runs two sub-commands who accept the same option, --config . I would like to create a third sub-command that can run the first two subcommands together, sequentially. Using argparse, I've created a subparser for each sub-command, as well as a third subparser, whose parents are the two sub-commands. Just to clarify: subcommand1 = subparsers.add_parser('subcommand1') subcommand1.add_argument('--config', help="The config") subcommand2 = subparsers.add_parser('subcommand2') subcommand2.add_argument('--config', help="The config") wrappercommand = subparsers.add_parser(

Using argparse with function that takes **kwargs argument

独自空忆成欢 提交于 2019-12-01 17:49:59
问题 I'm using argparse to take input and pass it to a function that takes as arguments two variables and **kwargs . Here's my function: import requests import sys import argparse def location_by_coordinate(LAT, LNG, **kwargs): if not kwargs: coordinate_url = "https://api.instagram.com/v1/locations/search?lat=%s&lng=%s&access_token=%s" % (LAT, LNG, current_token) r = requests.get(coordinate_url).text else: coordinate_url = "https://api.instagram.com/v1/locations/search?lat=%s&lng=%s&access_token=

Django's call_command fails with missing required arguments

雨燕双飞 提交于 2019-12-01 17:19:56
问题 I want to call a Django management command from one of my tests. I'm using django.core.management.call_command for this. And it doesn't work. I have a command with 4 required arguments. When I call it, it complains all arguments are missing even though I'm passing them: call_command('my_command', url='12', project='abc', website='zbb', title='12345') I get the base command error that --url, --project, --website and --title are missing. I did not specify a different destination for these

Python's argparse: How to use keyword as argument's name

半城伤御伤魂 提交于 2019-12-01 16:59:19
lambda has a keyword function in Python: f = lambda x: x**2 + 2*x - 5 What if I want to use it as a variable name? Is there an escape sequence or another way? You may ask why I don't use another name. This is because I'd like to use argparse : parser = argparse.ArgumentParser("Calculate something with a quantity commonly called lambda.") parser.add_argument("-l","--lambda",help="Defines the quantity called lambda", type=float) args = parser.parse_args() print args.lambda # syntax error! Script called with --help option gives: ... optional arguments -h, --help show this help message and exit -l

How to obtain argparse subparsers from a parent parser (to inspect defaults)

前提是你 提交于 2019-12-01 14:47:31
Suppose that I create a parser with a default value for an argument, and then give it a subparser with a further default value for an argument. In [1]: parser = argparse.ArgumentParser(description='test') In [2]: parser.add_argument("--test", dest="test", default="hello") Out[2]: _StoreAction(option_strings=['--test'], dest='test', nargs=None, const=None, default='hello', type=None, choices=None, help=None, metavar=None) In [3]: parser.get_default("test") Out[3]: 'hello' In [4]: subparsers = parser.add_subparsers(dest="command") In [5]: parser_other = subparsers.add_parser("other") In [6]:

Argparse in Jupyter Notebook throws a TypeError

丶灬走出姿态 提交于 2019-12-01 13:19:41
问题 Using argparse in a Jupyter Notebook throws a TypeError. The same code works fine if I execute the same code as a script. MWE: import argparse parser = argparse.ArgumentParser(description='Foo') parser.add_argument('--name', '-n', default='foo', help='foo') args = parser.parse_args() Result: TypeError: 'level' is an invalid keyword argument for this function 回答1: One solution is to parse an empty list of arguments: import argparse parser = argparse.ArgumentParser(description='Foo') parser.add

argparse optional positional argument and subparsers arguments

折月煮酒 提交于 2019-12-01 11:46:44
I have a python script that takes in an optional positional argument and has a few subcommands. Some of these subcommands require the positional argument, some don't. The problem I have appears when I try to use a subcommand that does not require the positional argument. Consider the following test file: import argparse argp = argparse.ArgumentParser() argp.add_argument('inputfile', type=str, nargs='?', help='input file to process') argp.add_argument('--main_opt1', type=str, help='global option') subp = argp.add_subparsers(title='subcommands', dest='parser_name', help='additional help',