Python Forum

Full Version: argparse
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have been playing with argparse for a a few hours and can't figure out something so simple.

import argparse
parser = argparse.ArgumentParser()

parser.add_argument("tst")

args = parser.parse_args()
print(args.tst)
What i then want to do is in linux:
python test_file_name.py hi

I then want to to print out "hi"
but i get this message instead:

"Error: unrecognized arguments: hi
Works for me:
$ cat test_file_name.py 
import argparse

parser = argparse.ArgumentParser()

parser.add_argument("tst")

args = parser.parse_args()
print(args.tst)
Output:
$ python test_file_name.py hi hi
Ohh, I think I was using python 2, not 3. Thanks, sorry for wasting your time.

I do have another question, could I make it where I add a "-" and a letter after the dash, then put the message?
For example python test_file_name.py -t hi
Then it prints "hi"
I like the "-" as its what is used in linux a lot.
(May-15-2019, 06:03 PM)2skywalkers Wrote: [ -> ]For example python test_file_name.py -t hi
Then it prints "hi"
I like the "-" as its what is used in linux a lot.
Sure but i don't use argparse,i can show you an other way with Click.
argparse is't bad it work well,just that i think Click dos a lot stuff better.
import click

@click.command()
@click.option('-t', '--string-to-echo', 'string')
def echo(string):
    click.echo(f'{string} or backwards {string[::-1]}')

if __name__ == '__main__':
    echo()
Output:
λ python hello.py -t hello hello or backwards olleh
A look at Click i had i while ago.
I like plumbum.cli. Very easy to use.