1

I've been trying to understand tutorials on how to parse arguments in Python using argparse. Is this how I would pass a command line input so I can run a function?

import argparse

parser = argparse.ArgumentParser(description='A test')
parser.add_argument("--a", default=1, help="Test variable")

args = parser.parse_args()

def foo():
    command_line_argument = args.a
    bar = 2*args.a
    print(bar)
    return

if "__name__" == "__main__" 
    try:
        while True:
        foo()
    except KeyboardInterrupt:
        print('User has exited the program')
gsb22
  • 2,112
  • 2
  • 10
  • 25

2 Answers2

2

That while True looks odd to me -- are you asking the reader to keep submitting inputs until they CTRL+C ? Because if so, argparse is the wrong thing to use: see Getting user input

If you intend a single argument then I'd move the parser stuff inside main, which is what gets executed when the script is run as a program as opposed to being imported.

Also, I'd pass a parameter to foo rather than the args block.

Lastly, I guess you're expecting to receive a number so you need type=int or similar.

import argparse


def foo(a):
    bar = 2*a
    print(bar)
    return

if __name__ == "__main__": 
    try:
        # set it up
        parser = argparse.ArgumentParser(description='A test')
        parser.add_argument("--a", type=int, default=1, help="Test variable")

        # get it
        args = parser.parse_args()
        a = args.a

        # use it
        foo(a)
    except KeyboardInterrupt:
        print('User has exited the program')

So:

$ python foo.py --a 1
2
  • Thank you! Sorry for the confusing code I was trying to come up with some example code to illustrate what I want. This is exactly what I want! – noobquestionsonly Feb 13 '20 at 17:20
0

below is in working state

import argparse
parser = argparse.ArgumentParser(description='A test')
parser.add_argument("--a", default=1, help="Test variable", type=int)

args = parser.parse_args()

def foo():
    command_line_argument = args.a
    bar = 2*args.a
    print(bar)
    return


if  __name__ == "__main__":
    try:
        while True:
            foo()
    except KeyboardInterrupt:
        print('User has exited the program')

if you run python your-filename.py --a=2 it will print 4 until you stop the execution.

Sanjay
  • 1,958
  • 2
  • 17
  • 25