简体   繁体   中英

Python: Calling function from command line using argparse

I am new to python. I am trying to implement a simple program that uses arguments to call various functions.

def function1(releaseid,path)
...

def function2(versionid)
...

Lets say those functions are in a.py, I would like to call those functions in other script called b.py.

I want to call this way:

python --function  function1 --version 10.23.401-Jun --path /test/common/releases
python --function  function2 --version 10.23.401-Jun 

How could we handle this to call function1 , function2 in a.py with required arguments? i found that we can handle this with argparse module. Can you please share some example?

If you want to use argparse, have a look on https://docs.python.org/3/howto/argparse.html

In the simpliest form it would be like

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--function", help="<description>",
                    action="store_true")
args = parser.parse_args()
if args.function == "function1":
    function1()
elif args.function == "function2":
    function2()

However, there are much better third-party libraries for building cli interfaces, for example https://click.palletsprojects.com/en/7.x/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM