Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run different python functions from command line

Tags:

python

I'm trying to run different functions from a python script(some with arguments and some without)

So far I have

def math(x):
   ans = 2*x
   print(ans)

def function1():
  print("hello")

if __name__ == '__main__':   
     globals()[sys.argv[1]]()

and in the command line if I type python scriptName.py math(2)

I get the error

File "scriptName.py", line 28, in <module>

globals()[sys.argv[1]]()

KeyError: 'mat(2)'

New to python and programming so any help would be apprecitated. This is also a general example...my real script will have a lot more functions.

Thank you

like image 587
Nemo Avatar asked Aug 24 '26 02:08

Nemo


1 Answers

Try this!

import argparse

def math(x):
    try:
        print(int(x) * 2)
    except ValueError:
        print(x, "is not a number!")


def function1(name):
    print("Hello!", name)


if __name__ == '__main__':
    # if you type --help
    parser = argparse.ArgumentParser(description='Run some functions')

    # Add a command
    parser.add_argument('--math', help='multiply the integer by 2')
    parser.add_argument('--hello', help='say hello')

    # Get our arguments from the user
    args = parser.parse_args()


    if args.math:
        math(args.math)

    if args.hello:
        function1(args.hello)

You run it from your terminal like so:

python script.py --math 5 --hello ari

And you will get

>> 10
>> Hello! ari

You can use --help to describe your script and its options

python script.py --help

Will print out

Run some functions

optional arguments:
  -h, --help     show this help message and exit
  --math MATH    multiply the integer by 2
  --hello HELLO  say hello

Read More: https://docs.python.org/3/library/argparse.html

like image 66
Ari Avatar answered Aug 26 '26 15:08

Ari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!