2

I am trying to work with argparse in python and I do not know how to call the program at command line to see if it works.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("DocID", type= int, help= "Insert DocID Here")
parser.add_argument("echo", help = "Enter in the FileName to be read")
args = parser.parse_args()
print args

This is my incredibly basic program that I am trying to use just to learn more about how argparse works. I just need to learn how and where to call the program to be able to use the arguments I give it.

Edit: To make my question more clear sorry. I have this code, but I do not know how to call the program as a whole so that I can run it. Like how would I run this in command line? Because when run just in IDLE it produces and error because of a lack of commands

2
  • 1
    What are you trying to do? Have you read that? Commented Aug 28, 2012 at 14:15
  • Argument names are usually preceded by a '--' or a '-'. Commented Aug 28, 2012 at 14:16

2 Answers 2

4

an ArgumentParser's parse_args method can take a list as input. That list is used for parsing the commandline arguments. So, a common idiom is:

args = parser.parse_args('-a -b -c --value=True'.split())

since str.split returns a list. ('a b c'.split() == ['a', 'b', 'c'])


Usually when you add arguments, you do so like this:

parser.add_argument('-a', '--a-long-name', type=int, ...)

Arguments without a - or -- in front are positional arguments, so both of your arguments are positional. You can see a little of what is happening if you do:

args = parser.parse_args(['1','foo'])
print args.DocID # 1
print args.echo  # foo

which is the same as calling your script as python youscript.py 1 foo (without the list inside parse_args).

Sign up to request clarification or add additional context in comments.

2 Comments

How can I make the script 'python youscript.py arg1 arg 2' work though. This is my real issue, that I get the python is not recognized as a command error
Then it seems that you have python installed in a non-standard place (outside of path). What OS are you using? If on *NIX, try the path to python pointed to by idle. In other words, head $(which idle) will have a path to python coded into the first line. try that path.
0

If you want to know the command line syntax of the script... just call it with --help, argparse automatically provides it for you.

⚫  gbin@sal tmp % python test.py --help
usage: test.py [-h] DocID echo

positional arguments:
  DocID       Insert DocID Here
  echo        Enter in the FileName to be read

optional arguments:
  -h, --help  show this help message and exit

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.