Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8221015
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T13:45:07+00:00 2026-06-07T13:45:07+00:00

In my python script, I want to be able to use an optional input

  • 0

In my python script, I want to be able to use an optional input parameter only when another optional parameter has been specified. Example:

$ python myScript.py --parameter1 value1
$ python myScript.py --parameter1 value1 --parameter2 value2

But NOT:

$ python myScript.py --parameter2 value2

How do I do this with argparse?

Thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T13:45:09+00:00Added an answer on June 7, 2026 at 1:45 pm

    Use a custom action:

    import argparse
    
    foo_default=None    
    
    class BarAction(argparse.Action):
        def __call__(self,parser,namespace,values,option_string=None):
            didfoo=getattr(namespace,'foo',foo_default)
            if(didfoo == foo_default):
                parser.error( "foo before bar!")
            else:
                setattr(namespace,self.dest,values)
    
    parser=argparse.ArgumentParser()
    parser.add_argument('--foo',default=foo_default)
    parser.add_argument('--bar',action=BarAction,help="Only use this if --foo is set")
    
    #testing.
    print parser.parse_args('--foo baz'.split())
    print parser.parse_args('--foo baz --bar cat'.split())
    print parser.parse_args('--bar dog'.split())
    

    This can even be done in a little easier to maintain way if you’re OK with relying on some undocumented behavior of argparse:

    import argparse
    
    parser=argparse.ArgumentParser()
    first_action=parser.add_argument('--foo',dest='cat',default=None)
    
    class BarAction(argparse.Action):
        def __call__(self,parser,namespace,values,option_string=None):
            didfoo=getattr(namespace,first_action.dest,first_action.default)
            if(didfoo == first_action.default):
                parser.error( "foo before bar!")
            else:
                setattr(namespace,self.dest,values)
    
    parser.add_argument('--bar',action=BarAction,
                        help="Only use this if --foo is set")
    
    #testing.
    print parser.parse_args('--foo baz'.split())
    print parser.parse_args('--foo baz --bar cat'.split())
    print parser.parse_args('--bar dog'.split())
    

    In this example, we get the default for foo and it’s destination from the action object returned by add_argument (add_argument’s return value isn’t documented anywhere that I can find). This is still a little fragile (If you want to specify a type= keyword to the --foo argument for example).

    Finally, you can check sys.argv before parsing.

    import sys
    if ("--parameter2" in sys.argv) and ("--parameter1" not in sys.argv):
        parser.error("parameter1 must be given if parameter2 is given")
    

    This gets a little more tricky if --parameter1 could also be triggered by --p1, but you get the idea. Then you could use

    if (set(sys.argv).intersection(('--p2',...)) and 
        not set(sys.argv).intersection(('--p1',...)))
    

    The advantage here is that it doesn’t require any particular order. (--p2 doesn’t need to follow --p1 on the commandline). And, as before, you can get the list of command strings that will trigger your particular action via the option_strings attribute returned by parser.add_argument(...). e.g.

    import argparse
    import sys   
    parser=argparse.ArgumentParser()
    action1=parser.add_argument('--foo')
    action2=parser.add_argument('--bar',
                                help="Only use this if --foo is set")
    
    argv=set(sys.argv)
    if (( argv & set(action2.option_strings) ) and 
          not ( argv & set(action1.option_strings) )):
                    #^ set intersection
         parser.error(' or '.join(action1.option_strings)+
                      ' must be given with '+
                      ' or '.join(action2.option_strings))
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to run a python script from within another. By within I mean
I'm new to Python and I want my Python script to be able to
I want my Python script to be able to read Unicode command line arguments
I have a python script that I want always to run in the background.
I have a Iron Python script that I want to run and then have
I want my python script to simultaneously accept POST variables and query string variables
I am with a python script. I want to open a file to retrieve
I want to set up a cron job to run a python script, but
I want to start a number of subprocesses in my Python script and then
I want to pass a datetime value into my python script on the command

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.