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!

Zeretil
  • 287
  • 2
  • 19
  • 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? – Peter DeGlopper Feb 13 '17 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 – Nullman Feb 13 '17 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. – Zeretil Feb 13 '17 at 18:50
  • @PeterDeGlopper, I would like to try out the rejecting, how do I do this? – Zeretil Feb 13 '17 at 18:50
  • http://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: http://stackoverflow.com/a/8107776/2337736 – Peter DeGlopper Feb 13 '17 at 19:07

1 Answers1

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.

Gustavo Gomes
  • 317
  • 5
  • 13