0

I am setting up a Python script to calculate a risk score. The script will need to be run from the command line and will include all the variables needed for the calculation.

The needed format is: python test.ipynb Age 65 Gender Male

Age and Gender are the variable names, with 65 (integer years) and Male (categorical) being the variables.

I am very new to Python, so the skill level is low. - Looked for examples - Read about getopt and optoparse - Attempted to write Python code to accomplish this

import sys, getopt

def main(argv):
   ageValue = 0
   genderValue = 0

   try:
      opts, args = getopt.getopt(argv,"",["Age","Gender"])
   except getopt.GetoptError:
      print ('Error, no variable data entered')
      sys.exit(2)
   for opt, arg in opts:
      if opt == "Age":
         ageValue = arg
      if opt == "Gender":
         genderValue = arg
   print ('Age Value is  ', ageValue)
   print ('Gender Value is ', genderValue)

This is the output from this code -

Age Value is 0

Gender Value is 0

The expected output is

Age Value is 65

Gender Value is Male

2 Answers 2

2

Argparse is what I use. Here's some code.

import argparse 

parser = argparse.ArgumentParser(description='Do a risk thing')
parser.add_argument('-a', '--age', dest='age', type=int, help='client age')
parser.add_argument('-g', '--gender', dest='gender', type=str, help='client gender')

args = parser.parse_args()

print('Age: {}\nGender: {}'.format(args.age, args.gender))

Usage python test.py --age 25 --gender male.

Note that this won't work with a python notebook. For that, I'm not sure of a solution. Also, you can really configure the heck out of argparse, so I'd recommend reading the docs.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, your example is quite clear. The structure of your code makes much more sense to me than the other examples I found.
2
import argparse 

if __name__ == "__main__"
   parser.add_argument('-age', required=True)
   parser.add_argument('-gender', required=True)
   args = vars(parser.parse_args())
   print(args['age'], args['gender'])


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.