1

I'm using argparse to use user arguments to run functions in my program which is running just fine. But I'm unable to run other generic functions which I'm calling in main(). It just skips those functions without running and showing output. How do I do it or where am I doing wrong ?

Let's say in below program I want functions mytop20 and listapps to be run using user arguments which runs fine if I remove the boilerplate main() function but my objective is run_in_main() function should run in main()

import argparse

def my_top20_func():
    print "Called my_top20_func"

def my_listapps_func():
    print "Called my_listapps_func"

def run_in_main():
    print "Called from main"

parser = argparse.ArgumentParser()
FUNCTION_MAP = {'top20' : my_top20_func,
                'listapps' : my_listapps_func }

parser.add_argument('command', choices=FUNCTION_MAP.keys())

args = parser.parse_args()

func = FUNCTION_MAP[args.command]
func()

if __name__ == "__main__":
    run_in_main()

As my use case is quite similar I have taken above code from here.

jagatjyoti
  • 699
  • 3
  • 10
  • 29
  • 1
    your code example doesn't clearly illustrate what you're trying to accomplish, and it seems like you're missing some indentation, since all `run_in_main()` will do is `print "Some func in main executed"` – raphael Aug 22 '17 at 17:39
  • What is `FUNCTION_MAP`? should it be `funcs_dict`? Have you left off the stuff that creates `args`? Have you tried moving that part into `run_in_main`? – hpaulj Aug 22 '17 at 18:47
  • @raphael As already mentioned, this is just a prototype of my real program. I just want to run run_in_main() function in main() which I'm unable to do. It skips all the time. – jagatjyoti Aug 23 '17 at 03:07
  • @hpaulj I have edited the question now and it's working fine. Without main() function everything is working fine but I want to run my function which is there in main(). – jagatjyoti Aug 23 '17 at 03:24

1 Answers1

2

Often the parse_args is put in the main section so it runs only when the file is used as a script, not when imported. With that in mind, I'd reorganize your script as:

def main(args):
    func = FUNCTION_MAP[args.command]
    func()

if __name__ == '__main__':
    args = parser.parse_args()
    main(args)
hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • If we consider running it as script then how do we run the function `run_in_main()` apart from what we call using user arguments ? – jagatjyoti Aug 23 '17 at 15:06
  • You can either construct an `args` like object (see the docs about `Namespace`), or change `main` to take a string, and pass `args.command`. – hpaulj Aug 23 '17 at 15:51