2

I have a python program that takes in many arguments and run. With argparse, I can define the arguments, their default values, their explanations, and it can be used as a convenient container. So it's all good for passing arguments from command line.

But can I also use it to pass the arguments from code, for API call?

THN
  • 3,351
  • 3
  • 26
  • 40
  • Look at the `args` `Namespace` object created by `parse_args()`. You can recreate that directly, e.g. `args = argparse.Namespace(foo='bar', arg1=12)`, etc. – hpaulj Jun 13 '19 at 17:02

4 Answers4

7

Yes, certainly argparse can be used to pass arguments both from command line and from code.

For example:

import argparse

# Define default values
parser = argparse.ArgumentParser()
parser.add_argument('--foo', default=1, type=float, help='foo')

# Get the args container with default values
if __name__ == '__main__':
    args = parser.parse_args()  # get arguments from command line
else:
    args = parser.parse_args('')  # get default arguments

# Modify the container, add arguments, change values, etc.
args.foo = 2
args.bar = 3

# Call the program with passed arguments
program(args)
THN
  • 3,351
  • 3
  • 26
  • 40
2

With vars() you can use your args like dictionaries.

from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument("-f", "--foo")
parser.add_argument("-b", "--bar")

args = vars(parser.parse_args())
print(f"args foo is {args['foo']}")
print(f"args bar is {args['bar']}")

Result when you execute and parse some arguments look like.

python3 test.py --foo cat --bar dog
args foo is cat
args bar is dog
King Peanut
  • 116
  • 3
1
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("-f", "--file", dest="filename",
                help="write report to FILE", metavar="FILE")
parser.add_argument("-q", "--quiet",
                action="store_false", dest="verbose", default=True,
                help="don't print status messages to stdout")

args = parser.parse_args()
Yash Shukla
  • 141
  • 6
0

When running this file from terminal, you can pass the arguments in the following manner:

python36 commandline_input.py 10

python36 commandline_input.py 10 --foo 12

The first positional argument is mandatory, the second is optional therefore you need a flag (--foo).

commandline_input.py:

import argparse


def main(mandatory_arg, optional_arg):
    # your program 
    pass


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    # mandatory
    parser.add_argument('bar', help='Some Bar help')
    # optional
    parser.add_argument('-f', '--foo', default='default foo value',
                        help='Some foo help')
    
    args = parser.parse_args()

    # mandatory args
    print(args.bar, '(man)')

    # optional args
    if args.foo:
        print(args.foo, '(opt)')
    
    # your API call
    main(args.bar, [args.foo])
Community
  • 1
  • 1
BramAppel
  • 1,346
  • 1
  • 9
  • 21