0

to make the question more clear, I am using Argparse to receive two optional arguments. I only want to use them if both are given, but I do not want to require them.

parser = argparse.ArgumentParser()
parser.add_argument("-d", "--destination", help="set the destination directory or disk.",)
parser.add_argument("-s", "--source", help="set the source directory or disk.")

What I was trying to do is check if either of those two was other than None, and from there run my code.

As I am here I guess you can figure out that I was unsuccesful. I don't think giving my horrible attempts at doing this is useful to anyone, since there is probably a uniform answer I couldn't find by Googling.

Thanks for looking at my question and possible answering it!

5
  • Do you want argparse to reject command lines if one is None and the other isn't, or do you just want an if/then? Commented Feb 13, 2017 at 18:41
  • you are probably looking for required=True i.e. parser.add_argument("-s", "--source", required=True, help="set the source directory or disk.") but this isn't pythonic for '-' parameters Commented Feb 13, 2017 at 18:46
  • @Nullman, as I stated I don't want to use required, because I have default values to use if they are both None. Commented Feb 13, 2017 at 18:50
  • @PeterDeGlopper, I would like to try out the rejecting, how do I do this? Commented Feb 13, 2017 at 18:50
  • stackoverflow.com/a/14350426/2337736 reports that argparse doesn't support that, so I guess the if version is the only option. Maybe using a custom error as shown here: stackoverflow.com/a/8107776/2337736 Commented Feb 13, 2017 at 19:07

1 Answer 1

1

Try this:

parser = argparse.ArgumentParser()
parser.add_argument("-d", "--destination", help="set the destination directory or disk.",)
parser.add_argument("-s", "--source", help="set the source directory or disk.")

args, leftovers = parser.parse_known_args()
if args.destination is not None and args.source is not None:
   # Do your code here

I think this is what you want, I wasn't able to test it but try it and I hope it was helpful.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.