6

I'm running into issues when using argparse. With below code, I expected args.dir to be a string, but instead I got an array. How can I get a string? Can anyone help?

#!/usr/bin/env python3

import sys
import argparse

#import mysql.connector

# Set version number
version = '1.0.0'

# Parse arguments supplied on the commandline
argparser = argparse.ArgumentParser(description=sys.argv[0])
argparser.add_argument('dir', nargs=1, type=str, help='directory to view')
args = argparser.parse_args()

# Print program name and version number to stdout
print(argparser.prog + " v" + version)
print('Creating index for: ' + args.dir[0])
2
  • 2
    List, not an array. Commented Aug 29, 2018 at 23:26
  • docs.python.org/3/library/argparse.html#nargs Note that nargs=1 produces a list of one item. This is different from the default, in which the item is produced by itself. Commented Aug 30, 2018 at 2:25

1 Answer 1

9

You indicated nargs=1 and even though you provided the value 1, argparse built you a list (like an array but not exactly the same thing). This is actually helpful because you can guarantee that when you indicate nargs, you will always get a list.

Remove the nargs parameter and you will get a string rather than a list.

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

1 Comment

This did the trick! Thanks. Also thanks for providing some extra insight in array vs list.

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.