Python Argparse: how to make an argument required if and only if one flag is given?
<p>I am wondering how can I make one argument required when one flag is given, and optional when that flag is not given?</p>

<pre><code>import argparse


parser = argparse.ArgumentParser()

parser.add_argument('-c', '--convert', action = 'store_true')
parser.add_argument('-l', '--lookup', action = 'store_true')
parser.add_argument('name', type = str) 

args = parser.parse_args()

if args.name:
    print(args.name)
if args.convert:
    print ("convert now!")
</code></pre>

<p>For example, in the codes above, I want <code>name</code> to be required, only when <code>-c</code> is given. When I run the program only with <code>-l</code>, then there is an error:</p>

<pre><code>$ python3 test.py -l
usage: test.py [-h] [-c] [-l] name
test.py: error: the following arguments are required: name
</code></pre>

<p>I have tried to use argument group to divide the arguments into two groups 1. <code>-c</code> and <code>name</code>; 2. <code>-l</code>, but it didn't really work.</p>

<p>Any suggestions are appreciated!</p>

<p>This isn't something <code>argparse</code> can enforce on its own. What you can do is define <code>name</code> to be optional, then check after parsing if your constraint is met.</p>

<pre><code>import argparse


parser = argparse.ArgumentParser()

parser.add_argument('-c', '--convert', action='store_true')
parser.add_argument('-l', '--lookup', action='store_true')
parser.add_argument('name', nargs='?') 

args = parser.parse_args()

# If args.name must be a non-empty string when given,
# you can use 'not args.name' in place of 'args.name is None'
if args.convert and args.name is None:
    parser.error("&lt;name&gt; required with --convert")

if args.name:
    print(args.name)
if args.convert:
    print ("convert now!")
</code></pre>

python python-3.x arguments argparse