0

I must be missing something really obvious, but I can't for the life of me spot it.

import argparse


def parse_args():
    parser = argparse.ArgumentParser(description="Copies selected files.")
    parser.add_argument(
        "-c", "--checksum", type=bool, default=False
    )
    parser.add_argument("source")
    parser.add_argument("target")
    return parser.parse_args()


def main():
    args = parse_args()
    print(args.checksum, args.source, args.target)


main()

>python file_proc.py source1 target1
False source1 target1

So far, so good.

>python file_proc.py -c source1 target1
usage: file_proc.py [-h] [-c CHECKSUM] source target
file_proc.py: error: the following arguments are required: target

Now, why doesn't it output True source1 target1? It must be right there in front of me, but I need another pair of eyes.

Thanks!

1
  • The type parameter is supposed to be a function, something that will transform the input string into a desired value. You have to write your own if you want to interpret strings like "yes" or "no" as True/False booleans. Commented Nov 5, 2020 at 16:39

2 Answers 2

1

The way you've coded basically means, that if you are passing -c, then you need to pass a bool in the args as well.

Hence your statement:

>python file_proc.py source1 target1
False source1 target1

works fine, because you didn't pass -c. So, it printed False.

But when you pass -c in the command-line, it needs another variable to be passed in argument. So do this:

>python file_proc.py -c d source1 target1
True source1 target1

This means a bool was passed as an argument, hence it prints True.

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

Comments

0

The argument declaration for --checksum means that following -c/--checksum, an actual boolean is passed in. For example, --checksum yes would "enable" the checksum; due to how bool interprets strings, any argument other than the empty string evaluates to True.

Use the store_true/store_false action to define an argument-less flag that is toggled on/off by being mentioned.

    parser.add_argument(
        "-c", "--checksum", action='store_true'
    )

1 Comment

I know it was something basic! It's meant to be a switch argument, so I indeed needed action='store_true'. Thanks!

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.