call specific function from command line and pass arguments


This Content is from Stack Overflow. Question asked by f0rd42

I have a script with several functions (before that I had one script per function)
Each function will require different arguments (some positional/mandatory, some optional).

I’d like to be able to call a specific function within the script and then hand over the argparse arguments.


python3 getSites host token

I thought that using

if __name__ == '__main__':

to use sys.argv[1] as the choice for the fuction and then within the function use:

def getSites():
parser = argparse.ArgumentParser(description="SentinelOne Site Statistics (#mianly for licnese usage")
parser.add_argument('host', type=str, help='REQUIRED: Please enter the  Host (i.e. everything after "https://" and before ""')
parser.add_argument('token', type=str, help='REQUIRED: Please enter your token (without the string "ApiToken")')
parser.add_argument('-s', '--savepath', type=str,
                help='OPTIONAL: full path of the directory where to write the resulting XLS file. Defaults to directory of the script itself')
parser.add_argument('-a', '--accountid', type=str,
                help='OPTIONAL: Enter the AccountID to query. Defaults to all accounts / sites the token user has access to')
f_args = parser.parse_args()

would work but when entering e.g.

python3 getSites firsthost 98456984652984652984652985

I get error: unrecognized arguments: 98456984652984652984652985

My Questions:

  • Is it possible to archive this without the “overcomplicated” -c switch when calling the script?
  • should I rather go with moving the required arguments from argparse into the function? i.e. getsites(host, token) and then use argparse only for the optional arguments?

Benefit of the second method would be that I could also call the function from within a python script, not only from command line. On the other hand: the user would need to know exactly what they have to provide, as that won’t be shown when runnign the script with -h

I’m a bit confused here and would appreciate and help for a newbie.


This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?