Search code examples
pythonpython-3.xfunctionargumentsprogram-entry-point

Pass argument from main() to different function - Python 3.6


I am experimenting with the argparse module and I am having trouble understanding how to pass arguments from the parser constructed in main() to a new function that will use the arguments. I have tried reading some books and documentation on this topic, but I only feel more confused. I have pasted my code below.

CODE:

import argparse

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--skip", "-s", help="Skip updates to configuration.", 
                       action="store_true")
    args = parser.parse_args()


def config_check(*pass args here from main*):
    if args.skip:
        print("Not making modifications!")
    else:
        print("Making modifications!")

if __name__ == "__main__":
    main()

Solution

  • Just like how you would pass any other argument.

    import argparse
    
    def main():
        parser = argparse.ArgumentParser()
        parser.add_argument("--skip", "-s", help="Skip updates to configuration.", 
                           action="store_true")
        args = parser.parse_args()
        config_check(args)
    
    
    def config_check(args):
        if args.skip:
            print("Not making modifications!")
        else:
            print("Making modifications!")
    
    if __name__ == "__main__":
        main()