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?

1
  • 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. Commented Jun 13, 2019 at 17:02

4 Answers 4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

parse_args([]) is better (equivalent to an empty sys.argv[1:] list).
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

Comments

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()

4 Comments

I want to pass values from code like API call, not from command line.
How to pass in arguments from either command line or API call in python?
Ok, I'll try to Give your answer.
Thanks. Actually I realized I just lacked of coffee and asked the wrong question.
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])

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.