0

So, I wrote a script, to produce a configuration file and a json file if the argument --json is set to True. My code works well for all cases except when I explicitly pass the --json argument as False. It goes on to produce the json file anyway.

def parse_args():
    parser = argparse.ArgumentParser(description='Analyze a github repo')
    parser.add_argument('org', nargs='?', help = 'name of the organisation', default='twitter')

    parser.add_argument('--json', dest='json', type=bool, help='flag to specify if a json file is to be created', nargs='?', default=False, const=False)
    args = parser.parse_args()
    return args


def main():
    if sys.argv[1] == '':
        err= 'The script must be run with atleast one argument'
        sys.stderr.write(err)
        sys.exit(1)
    print(len(sys.argv))
    args = parse_args()
    org_name=''
    for e in str(args.org):
        if e.isalpha():
        org_name+=e
    print(args.json)
    if args.json==True:
        create_json(org_name)
    create_config(args.org, args.json)

I run the script as :

python3 script.py twitter --json False

where twitter is a sample organisation name, it can be anything.

Where am I making an error?

Karan Singh
  • 1,114
  • 1
  • 13
  • 30
  • For one thing it's not idiomatic to use `== True`, just `if args.json:`. But note that `bool('False')` evaluates truthy, as it's a non-empty string. – jonrsharpe Mar 15 '18 at 08:32
  • I had used if args.json: during debugging, just changed it to see if it would make any difference. But I am passing a boolean value on the command line, which I specify with type = bool. So am I not evaluating bool(False) instead of bool('False') ? – Karan Singh Mar 15 '18 at 08:42
  • 1
    No, you aren't. The `type` parameter, as documented, is a callable that takes a single *string* and returns whatever the value should be. It doesn't tell Python to do any other magic conversion. Note that a more idiomatic CLI might treat `--json` as a flag, using `store_true`, so you don't have to pass True or False to it. – jonrsharpe Mar 15 '18 at 08:53

0 Answers0