Python Forum
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
Reply
#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
Reply
#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.
Reply
#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.
Reply
#5
I like plumbum.cli. Very easy to use.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Bug argparse io issue pyDream 1 131 Mar-27-2024, 06:04 PM
Last Post: snippsat
  Not able to figure out what is wrong with argparse radioactive9 31 8,214 Mar-16-2022, 07:50 PM
Last Post: deanhystad
  argparse --help in one line. Denial 1 1,933 Sep-20-2020, 03:38 PM
Last Post: deanhystad
  Argparse error when inputting values tqader 2 2,822 Sep-11-2020, 07:42 PM
Last Post: buran
  Why this pycharm warning for argparse formatter_class value? pjfarley3 2 2,081 Sep-09-2020, 05:23 AM
Last Post: pjfarley3
  Can argparse support undocumented options? pjfarley3 3 2,121 Aug-14-2020, 06:13 AM
Last Post: pjfarley3
  In ArgParse, can two compatible formatter_class values be used? pjfarley3 2 2,522 Jul-31-2020, 02:01 PM
Last Post: pjfarley3
  Why am I getting KeyError 'file' when using argparse? Mike Ru 1 3,030 Jun-09-2019, 04:48 PM
Last Post: metulburr
  How can I get some arguments using argparse? Mike Ru 0 1,842 Jun-05-2019, 12:57 PM
Last Post: Mike Ru
  argparse and imported modules spatialdawn 2 5,387 Dec-01-2018, 12:35 PM
Last Post: spatialdawn

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020