argparse

Python argparse conditional requirements

吃可爱长大的小学妹 提交于 2019-12-03 23:32:08
How do I set up argparse as follows: if -2 is on the command line, no other arguments are required if -2 is not on the command line, -3 and -4 arguments are required For example, -2 [good] -3 a -4 b [good] -3 a [not good, -4 required] -2 -5 c [good] -2 -3 a [good] There are a number of similar questions here, but either they don't address this situation or I don't understand. Python 2.7 if that matters. A subparser (as suggested in comments) might work. Another alternative (since mutually_exclusive_group can't quite do this) is just to code it manually, as it were: import argparse def main():

argparse argument order

﹥>﹥吖頭↗ 提交于 2019-12-03 22:49:52
I have a little problem. I use argparse to parse my arguments, and it's working very well. To have the args, I do : p_args = parser.parse_args(argv) args = dict(p_args._get_kwargs()) But the problem with p_args is that I don't know how to get these arguments ordered by their position in the command line, because it's a dict. So is there any possibility to have the arguments in a tuple/list/ordered dict by their order in the command line? To keep arguments ordered, I use a custom action like this: import argparse class CustomAction(argparse.Action): def __call__(self, parser, namespace, values,

Python - Difference between docopt and argparse

浪尽此生 提交于 2019-12-03 22:30:21
I have to write a command-line interface and I've seen I can use docopt and argparse . I would like to know what are the main differences between the two so that I can make an enlightened choice. Please stick to the facts. I don't want Wow. docopt. So beautiful. Very useful. reindeer Docopt parses a doc string, whereas argparse constructs its parsing by creating an object instance and adding behaviour to it by function calls. Example for argparse: parser = argparse.ArgumentParser() parser.add_argument("operation", help="mathematical operation that will be performed", choices=['add', 'subtract'

Namespace, argparse, and usage

五迷三道 提交于 2019-12-03 22:17:37
This is really a few questions: Is there a reason argparse uses a namespace instead of a dictionary? Assuming I have a class with __init__(self, init_method, *args) . The init_method parameter tells the init_function which way I want to initialize the class, while arg parameter gives all the arguments neccesary for the init. The arguments may be different for different methods. Should I use a dictionary, or a namespace? Assuming that I use a namespace, how do I pass the namespace to __init__() ? Sven Marnach The designers of arparse apparently felt it would be more convenient to access

Most pythonic way of accepting arguments using optparse

﹥>﹥吖頭↗ 提交于 2019-12-03 16:33:44
I currently have a python file that utilizes sys.argv[1] to accept a string at the command line. It then performs operations on that string and then returns the modified string to the command line. I would like to implement a batch mode option in which I can provide a file of strings (one per line, fwiw) and have it return to the command line so that I can redirect the output doing something like $ python script.py -someflag file.txt > modified.txt while still retaining the current capabilities. I am only running 2.6, so argparse is not an option. The tutorials I have seen either use argparse,

Python argparse as a function

泄露秘密 提交于 2019-12-03 15:57:26
Is there anything inherently wrong with getting command-line arguments in this way? I mean by putting the argument parsing into its own function. Would it be considered non-Pythonic or more so? #!/usr/bin/python import argparse def getArgs(argv=None): parser = argparse.ArgumentParser(description="calculate X to the power of Y") group = parser.add_mutually_exclusive_group() group.add_argument("-v", "--verbose", action="store_true") group.add_argument("-q", "--quiet", action="store_true") parser.add_argument("x", type=int, help="the base") parser.add_argument("y", type=int, help="the exponent")

Control formatting of the argparse help argument list?

自作多情 提交于 2019-12-03 14:41:22
问题 import argparse parser = argparse.ArgumentParser(prog='tool') args = [('-u', '--upf', 'ref. upf', dict(required='True')), ('-s', '--skew', 'ref. skew', {}), ('-m', '--model', 'ref. model', {})] for args1, args2, desc, options in args: parser.add_argument(args1, args2, help=desc, **options) parser.print_help() Output: usage: capcheck [-h] -u UPF [-s SKEW] [-m MODEL] optional arguments: -h, --help show this help message and exit -u UPF, --upf UPF ref. upf -s SKEW, --skew SKEW ref. skew -m MODEL

How to set custom output handlers for argparse in Python?

元气小坏坏 提交于 2019-12-03 14:40:29
I have configured logger to print both onto terminal stdout and to a file so I can have an archive of logging messages that I can refer to. That is easily accomplished by adding a FileHandler to your logging object. Easy peasy. What I want to accomplish now is to make argparse log also to the same file along with logs to stdout when it encounters parsing errors. So far it only prints to stdout . I looked in the argparse documentation but I can't find anything about setting a different output stream or pipe for argparse . Is it possible to do? How? Looking at the argparse.py source code there

Python’s argh library: preserve docstring formatting in help message

馋奶兔 提交于 2019-12-03 13:32:56
While searching for faster ways to parse command-line arguments in my scripts I came across the argh library . I really like the features of argh but I’ve encountered one drawback that stops me from using it, and this has to do with the default help message that gets displayed if I’m invoking the —help option: per default the function’s docstring is displayed on top of the arguments list. This is great, however the initial formatting is lost. See, for example, the following example script import argh def func(foo=1, bar=True): """Sample function. Parameters: foo: float An example argument. bar

argparse — requiring either 2 values or none for an optional argument

不问归期 提交于 2019-12-03 13:02:49
I'm trying to make an optional argument for a script that can either take no values or 2 values, nothing else. Can you accomplish this using argparse? # desired output: # ./script.py -a --> works # ./script.py -a val1 --> error # ./script.py -a val1 val2 --> works version 1 -- accepts 0 or 1 values: parser = argparse.ArgumentParser() parser.add_argument("-a", "--action", nargs="?", const=True, action="store", help="do some action") args = parser.parse_args() # output: # ./script.py -a --> works # ./script.py -a val1 --> works # ./script.py -a val1 val2 --> error version 2 - accepts exactly 2