Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 argparse
#1
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
Quote
#2
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
Quote
#3
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.
Quote
#4
(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.
Quote
#5
I like plumbum.cli. Very easy to use.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  argparse and imported modules spatialdawn 2 327 Dec-01-2018, 12:35 PM
Last Post: spatialdawn
  Generating web page from argparse parameters gontajones 3 360 Nov-13-2018, 08:04 PM
Last Post: nilamo
  Usage of argparse with a single option Otbredbaron 3 735 Feb-24-2018, 07:28 PM
Last Post: metulburr
  Argparse niru 5 1,161 Oct-11-2017, 12:38 PM
Last Post: metulburr

Forum Jump:


Users browsing this thread: 1 Guest(s)