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')
2
  • It's if __name__ == '__main__':, you've got it the wrong way around. Commented Feb 13, 2020 at 16:37
  • The parsing should be done inside the if block. Commented Feb 13, 2020 at 16:42

2 Answers 2

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

1 Comment

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!
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.

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.