argparse

Using Argparse with Google Admin API

我的未来我决定 提交于 2019-12-01 21:16:38
I am using Google's Python API to pull down auditing information, but I can't get the parent group arguments for argparse (which appear to be required for API access) and my own arguments (e.g. passing in a date) to work together. Code: import pprint import sys import re import httplib2 import json import collections import argparse from oauth2client import client from apiclient import sample_tools from apiclient import discovery from oauth2client.client import AccessTokenRefreshError from oauth2client.client import OAuth2WebServerFlow from oauth2client.file import Storage from oauth2client

argparse on demand imports for types, choices etc

微笑、不失礼 提交于 2019-12-01 20:53:01
I have quite a big program which has a CLI interaction based on argparse , with several sub parsers. The list of supported choices for the subparsers arguments are determined based on DB queries, parsing different xml files, making different calculations etc, so it is quite IO intensive and time consuming. The problem is that argparse seems to fetch choices for all sub parser when I run the script, which adds a considerable and annoying startup delay. Is there a way to make argparse only fetch and validate choices for the currently used sub parser? One solution could be to move all the

Using argparse with function that takes **kwargs argument

十年热恋 提交于 2019-12-01 20:47:38
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=%s" % (LAT, LNG, current_token) for key, value in kwargs.iteritems(): if 'DISTANCE' in kwargs: distance

Is there a way to create argument in python's argparse that returns true in case no values given

☆樱花仙子☆ 提交于 2019-12-01 20:47:30
Currently --resize flag that I created is boolean, and means that all my objects will be resized: parser.add_argument("--resize", action="store_true", help="Do dictionary resize") # ... # if resize flag is true I'm re-sizing all objects if args.resize: for object in my_obects: object.do_resize() Is there a way implement argparse argument that if passed as boolean flag ( --resize ) will return true, but if passed with value ( --resize 10 ), will contain value. Example: python ./my_script.py --resize # Will contain True that means, resize all the objects python ./my_script.py --resize <index> #

Python argparse : how to detect duplicated optional argument?

守給你的承諾、 提交于 2019-12-01 20:42:33
I'm using argparse with optional parameter, but I want to avoid having something like this : script.py -a 1 -b -a 2 Here we have twice the optional parameter 'a', and only the second parameter is returned. I want either to get both values or get an error message. How should I define the argument ? [Edit] This is the code: import argparse parser = argparse.ArgumentParser() parser.add_argument('-a', dest='alpha', action='store', nargs='?') parser.add_argument('-b', dest='beta', action='store', nargs='?') params, undefParams = self.parser.parse_known_args() hpaulj append action will collect the

Stop argparse from globbing filepath

冷暖自知 提交于 2019-12-01 20:06:16
问题 I am using python argparse with the following argument definition: parser.add_argument('path', nargs=1, help='File path to process') But when I enter my command with a wildcard argument, argparse globs all the file paths and terminates with an error. How do I get argparse not to glob the files? 回答1: How do I get argparse not to glob the files? You don't. You get the shell to stop globbing. However. Let's think for a moment. You're saying this in your code parser.add_argument('path', nargs=1,

Optional positional arguments with Python's argparse

吃可爱长大的小学妹 提交于 2019-12-01 19:47:50
Trying to parse optional positional arguments I ran into following issue: Example: import argparse parser = argparse.ArgumentParser() parser.add_argument('infile') parser.add_argument('outfile', nargs='?') parser.add_argument('-v', action='store_true') print(parser.parse_args()) Output: $ ./x.py -v in out Namespace(infile='in', outfile='out', v=True) $ ./x.py in out -v Namespace(infile='in', outfile='out', v=True) $ ./x.py in -v out usage: x.py [-h] [-v] infile [outfile] x.py: error: unrecognized arguments: out Why is the third program invocation not accepted? Is this a restriction of argparse

Use dictionary for Python argparse

假装没事ソ 提交于 2019-12-01 19:24:57
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)) >>> parse(['-v', 'on']) <type 'str'>: on >>> parse(['-v', 'off']) <type 'str'>: off >>> parse(['-v',

Explanation for argparse python modul behaviour: Where do the capital placeholders come from?

蹲街弑〆低调 提交于 2019-12-01 19:07:56
I am trying to write a command line interface (for the first time) and after reading up about argparse , optparse and getopt I chose argparse because of several recommendations here on SO and elswhere in the net. Adapting a little of the advice of Mr. van Rossum I hooked up my first command line interface like this: def main(argv=None): if argv is None: argv = sys.argv desc = u'some description' parser = argparse.ArgumentParser(description=desc) parser.add_argument('-s', '--search', help='Search for someone.') parser.add_argument('-c', '--do_something_else', help='Do something else.') args =

Using unittest to test argparse - exit errors

徘徊边缘 提交于 2019-12-01 19:01:46
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's redundant given that argparse exits upon error? #!/usr/bin/env python3 import argparse import