Fix Python – Require either of two arguments using argparse

import argparse

pa = argparse.ArgumentParser()

print pa.parse_args(‘–foo 1’.split())

how do I

make at least one of “foo, bar” mandatory: –foo x, –bar y and –foo x –bar y are fine
make at most one of “foo, bar” mandatory: –foo x or –bar y are fine, –foo x –bar y is not


Fix Python – Python argparse ignore unrecognised arguments

Optparse, the old version just ignores all unrecognised arguments and carries on. In most situations, this isn’t ideal and was changed in argparse. But there are a few situations where you want to ignore any unrecognised arguments and parse the ones you’ve specified.
For example:
parser = argparse.ArgumentParser()
parser.add_argument(‘–foo’, de….

Fix Python – Python argparse: default value or specified value

I would like to have a optional argument that will default to a value if only the flag is present with no value specified, but store a user-specified value instead of the default if the user specifies a value. Is there already an action available for this?
An example:
python –example
# args.example would equal a default value of 1

Fix Python – Display help message with Python argparse when script is called without any arguments

Assume I have a program that uses argparse to process command line arguments/options. The following will print the ‘help’ message:
./myprogram -h

./myprogram –help

But, if I run the script without any arguments whatsoever, it doesn’t do anything. What I want it to do is to display the usage message when it is called with no arguments. How i….

Fix Python – Argparse: Required arguments listed under “optional arguments”?

I use the following simple code to parse some arguments; note that one of them is required. Unfortunately, when the user runs the script without providing the argument, the displayed usage/help text does not indicate that there is a non-optional argument, which I find very confusing. How can I get python to indicate that an argument is not optiona….

Fix Python – How to insert newlines on argparse help text?

I’m using argparse in Python 2.7 for parsing input options. One of my options is a multiple choice. I want to make a list in its help text, e.g.
from argparse import ArgumentParser

parser = ArgumentParser(description=’test’)

parser.add_argument(‘-g’, choices=[‘a’, ‘b’, ‘g’, ‘d’, ‘e’], default=’a’,
help=”Some option, where\n”
” a = a….

Fix Python – Python argparse command line flags without arguments

How do I add an optional flag to my command line args?
eg. so I can write

python -w

I tried

But I just get an error message saying
Usage [-w W]
error: argument -w: expected one argument

which I take it means that it wants an argument value for the -w option. What’s the way of just acc….