Run python script with some of the argument that are optional

后端 未结 4 852
慢半拍i
慢半拍i 2021-02-06 04:53

I have gone through the sys documentation, however there is something that is still unclear to me. I have looked for some similar question on stackoverflow, but I h

4条回答
  •  渐次进展
    2021-02-06 05:22

    Using Argparse

    I suggest you use argparse (and here is the tutorial ). Saves you having to manually check for the existence of parameters. Moreover argparse gives you the --help argument as a freebie, which will read the help="" string defined for each argument, if provided.

    Sample Program

    In your case you have three mandatory (positional) argument and three optional ones. A sample argparse code would look like this:

    #!/usr/bin/python
    # coding: utf-8
    
    import argparse
    
    def parseArguments():
        # Create argument parser
        parser = argparse.ArgumentParser()
    
        # Positional mandatory arguments
        parser.add_argument("creditMom", help="Credit mom.", type=float)
        parser.add_argument("creditDad", help="Credit dad.", type=float)
        parser.add_argument("debtMom", help="Debt mom.", type=float)
    
        # Optional arguments
        parser.add_argument("-dD", "--debtDad", help="Debt dad.", type=float, default=1000.)
        parser.add_argument("-s", "--salary", help="Debt dad.", type=float, default=2000.)
        parser.add_argument("-b", "--bonus", help="Debt dad.", type=float, default=0.)
    
        # Print version
        parser.add_argument("--version", action="version", version='%(prog)s - Version 1.0')
    
        # Parse arguments
        args = parser.parse_args()
    
        return args
    
    def example(credit_mom, credit_dad, debt_mom, debt_dad = 1000, salary = 2000, bonus = 0):
        total_gain = salary + credit_dad + credit_mom + bonus
        total_loss = debt_dad + debt_mom
    
        return total_gain - total_loss
    
    if __name__ == '__main__':
        # Parse the arguments
        args = parseArguments()
    
        # Raw print arguments
        print("You are running the script with arguments: ")
        for a in args.__dict__:
            print(str(a) + ": " + str(args.__dict__[a]))
    
        # Run function
        print(example(args.creditMom, args.creditDad, args.debtMom, args.debtDad, args.salary, args.bonus))
    

提交回复
热议问题