D Prat
D Prat

Reputation: 362

How to access to argparse positional arguments through namespace object in Python

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...

Upvotes: 2

Views: 3201

Answers (1)

doctorlove
doctorlove

Reputation: 19232

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.

Upvotes: 5

Related Questions