2

I'm trying to use a positional argument through argparse, but i cannot access to this argument value... I tried to look at the documentation from python about argparse but i didn't found anything really clear nor on the different thread...

So here is my code :

parser = argparse.ArgumentParser(description='valid arguments')
parser.add_argument('file_liste', type=str, help='give a valid list')
args = parser.parse_args()
print(args)

and here is the result i get:

Namespace(file_liste='my_list.txt')

that's my command line to launch my script:

python my_script.py my_list.txt

What i want is that my script take a txt file as an argument, to read it, but i can't access to this value that should be stored in the variable called 'file_liste'.

I tried this, but i get an error:

print(args[0], "this is args[0]")
TypeError: 'Namespace' object does not support indexing

It's probably a stupid thing, but i didn't found any answer that i could understand...

3
  • 3
    Try args.file_liste Commented Aug 29, 2018 at 10:31
  • Well, it works... I knew I was missing something, sorry for this ! Commented Aug 29, 2018 at 11:59
  • related (names with hyphens): stackoverflow.com/q/63255485 Commented Feb 1, 2024 at 13:43

1 Answer 1

5

args gives you the arguments, which as the error says, doesn't support indexing. It gives you named items, for example,

args.file_liste

will be the file list you asked for.

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.